ios objc_msgSend简单使用

  • Post author:
  • Post category:其他


引入头文件


#import


<objc/runtime.h>


#import


<objc/message.h>



1. 以前未使用objc_msgSend时,我们是这样调用testRuntime函数的

- (void)runTimeClicked
{
    [self testRuntime];
}


- (void)testRuntime
{
    NSLog(@"-----timeruntiem---");
}

2.现在使用objc_msgSend,实现以下方法就可以直接调用testRuntime函数了。

- (void)runTimeClicked
{
    //objc_msgSend(self,@selector(testRuntime));
    SEL testFunc = NSSelectorFromString(@"testRuntime");
    
    //ios8下特殊写法
    ((void(*)(id,SEL, id,id))objc_msgSend)(self, testFunc, nil, nil);
}


- (void)testRuntime
{
    NSLog(@"-----timeruntiem---");
}


为什么我们不直接用1中的直接调用方法了,要学习2中的运行时方法?


因为当你们的APP是个很大的项目时,需要多人协作,各自模块(framework,lib.a格式)各自开发人员去开发。为了减少各自模块之前的耦合度,实现分离,此时上面的运行时方法,就是很好的解决方案。



版权声明:本文为robinson_911原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。