iOS runtime动态添加方法

1. 为什么要给一个类动态添加方法?

  如果一个类有很多的方法, 当我们加载这个类的时候会比较消耗内存资源, 需要给每个方法生成映射表,  我们可以动态给这个类添加方法

2. 一个类动态添加方法的好处?

  1. 减少加载类是内存的消耗

  2. 可以调用一个未实现的方法和去除报错

3. 主要使用的api

  1. + (BOOL)resolveInstanceMethod:(SEL)sel; // 被调用的方法实现部分没有找到,而消息转发机制启动之前的这个中间时刻。

  2. class_addMethod(<#Class  _Nullable __unsafe_unretained cls#>, <#SEL  _Nonnull name#>, <#IMP  _Nonnull imp#>, <#const char * _Nullable types#>)               // 为一个类动态添加方法

  <#Class  _Nullable __unsafe_unretained cls#>: 为哪一个类添加方法  

  <#SEL  _Nonnull name#>: 方法的注册名称 

  <#IMP  _Nonnull imp#>: 方法的指针, 可以通过class_getMethodImplementation(Class cls, SEL name)来获取

  <#const char * _Nullable types#>: 方法返回值类型, 入参; 比如: "v@:@", v: 返回的参数类型, @:代表自己, @一个参数

4. 调用performSelector: 是运行时系统负责去找方法的,在编译时候不做任何校验;如果直接调用编译是会自动校验。

5. 实例:

  //动态添加一个方法

  Person *p = [[Person alloc]init];

  class_addMethod([Person class], @selector(printPerson), class_getMethodImplementation([ViewController class], @selector(find)), "v@:");

  [p performSelector:@selector(printPerson)];



        

 

猜你喜欢

转载自www.cnblogs.com/diweinan/p/9718348.html