zoukankan      html  css  js  c++  java
  • RunTime(消息机制) + RunTime(消息转发)

                                                                     一.消息机制
    1.在viewDidLoad中直接用 performSelector:@selector(doSomething) 来调用doSomething方法时,会发现找不到这个方法而奔溃.此时,我们可以在resolveInsantanceMethod:(SEL)see 方法中获取这个所有在运行时阶段的方法,在这个方法中只需要判断一下,将这个方法获取,并且运用Runtime 的 class_addMethod 的方法来将方法和响应函数绑定,进而达到为某一个类添加方法的目的.
    - (void)viewDidLoad {
        [superviewDidLoad];
        [selfperformSelector:@selector(doSomething)];
    }
    //1.对象在收到无法解读的消息后,会调用resolveInstanceMethod
    //2.再用class_addMethod 将调用的方法名字和制定函数相关联
    + (BOOL)resolveInstanceMethod:(SEL)sel {
        if (sel == @selector(doSomething)) {
            NSLog(@"add method here");
            class_addMethod([selfclass], sel, (IMP)dynamicMethodIMP, "v@:");
            returnYES;
        }
        return [superresolveInstanceMethod:sel];
    }
    //函数
    void dynamicMethodIMP (idself,SEL_cmd) {
        NSLog(@"doSomething SEL");
    }
    + (BOOL)resolveClassMethod:(SEL)sel {
        NSLog(@">> Class resolving %@",NSStringFromSelector(sel));
        return [superresolveClassMethod:sel];
    }
                                  二.消息转发
    #import "ViewController.h"

    @interfaceViewController ()

    @end

    @implementation ViewController

    - (void)viewDidLoad {
        [superviewDidLoad];
        [selfperformSelector:@selector(messageViewMethod)];
    }

    /**
     *  @author zhouyantong
     *
     *  @brief 在这个方法中并没有找到或者实现相应的方法,那么消息会往下传递,在转发方法中看别的界面是否有这个方法
     *
     */
    + (BOOL)resolveInstanceMethod:(SEL)sel {
        return [superresolveInstanceMethod:sel];
    }

    - (id)forwardingTargetForSelector:(SEL)aSelector {
        Class class = NSClassFromString(@"MessageViewController");
        UIViewController *vc = class.new;
        if (aSelector == NSSelectorFromString(@"messageViewMethod")) {
            NSLog(@"MessageVC do this!");
            return vc;
        }
        returnnil;
    }

    - (void)didReceiveMemoryWarning {
        [superdidReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
     
     
     
    #import "MessageViewController.h"

    @interfaceMessageViewController ()

    @end

    @implementation MessageViewController

    - (void)viewDidLoad {
       
    }

    - (void)messageViewMethod {
        NSLog(@"This is receive method!");
    }
    @end
     
  • 相关阅读:
    iOS开发之集成iOS9中的Core Spotlight Framework搜索App的内容
    Masonry介绍与使用实践(快速上手Autolayout)(转)
    NSUserDefaults 简介,使用 NSUserDefaults 存储自定义对象(转)
    UIViewController 中的 willMoveToParentViewController和didMoveToParentViewController的使用(转载)
    iOS7开发-Apple苹果iPhone开发Xcode官方文档翻译
    iOS在UITableView全面解析
    iOS UILabel详解(转载)
    UIScrollViewDelegate-委托方法API
    wordpress通过代码禁用IE8, IE9,IE10等IE浏览器兼容视图模式(Compatibility View)
    LNMP安装WordPress3.4.2看不到主题解决方法
  • 原文地址:https://www.cnblogs.com/zhouyantongiOSDev/p/5250756.html
Copyright © 2011-2022 走看看