美文网首页
runtime方法交换

runtime方法交换

作者: Chris_C | 来源:发表于2017-02-22 07:04 被阅读10次

    方法交换的作用:
    一、在不修改源代码的基础上,对方法内的代码进行修改
    二、

    - (void)viewDidLoad {
    [super viewDidLoad];
    objc_msgSend(self,@selector(test));
    
    [self say];
    [self mySay];
    
    [self changeMethod];
    
    [self say];
    [self mySay];
    }
    
    - (void)test
    {
        NSLog(@"test");
    }
    
    - (void)changeMethod
    {
        /*
         class_getInstanceMethod     得到类的实例方法
         class_getClassMethod          得到类的类方法
         */
        Method say1 = class_getInstanceMethod([ViewController    class], @selector(say));
        Method mySay1 = class_getInstanceMethod([ViewController class], @selector(mySay));
        method_exchangeImplementations(say1, mySay1);
    }
    
    - (void)say
    {
         NSLog(@"%s",__FUNCTION__);
    }
    
    - (void)mySay
    {
        NSLog(@"%s",__FUNCTION__);
    }
    
    测试结果:
    2016-08-11 16:17:16.997 RuntimeTest[3199:126416] test
    2016-08-11 16:17:16.997 RuntimeTest[3199:126416] -    [ViewController say]
    2016-08-11 16:17:16.997 RuntimeTest[3199:126416] - [ViewController mySay]
    2016-08-11 16:17:16.998 RuntimeTest[3199:126416] -[ViewController mySay]
    2016-08-11 16:17:16.998 RuntimeTest[3199:126416] -[ViewController say]

    相关文章

      网友评论

          本文标题:runtime方法交换

          本文链接:https://www.haomeiwen.com/subject/gplssttx.html