iOS用runtime给一个类动态添加方法 ---class_addMethod
先介绍下class_addMethod这个fangfa
- /**
- * Adds a new method to a class with a given name and implementation.
- *
- * @param cls The class to which to add a method.
- * @param name A selector that specifies the name of the method being added.
- * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.
- * @param types An array of characters that describe the types of the arguments to the method.
- *
- * @return YES if the method was added successfully, otherwise NO
- * (for example, the class already contains a method implementation with that name).
- *
- * @note class_addMethod will add an override of a superclass's implementation,
- * but will not replace an existing implementation in this class.
- * To change an existing implementation, use method_setImplementation.
- */
- OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp,
- const char *types)
- OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);
这是文档
描述就是:给一个类添加一个新的方法和该方法的具体实现
参数:
第一个
Class cls
cls :你要添加新方法的那个类
第二个
SEL name
name :要添加的方法
第三个
IMP imp
imp:指向实现方法的指针 就是要添加的方法的实现部分
第四个
const char *types
*types:我们要添加的方法的返回值和参数 叫 type encodings 这个东西怎么写我就不说了 可以去查 在这里我有一个懒办法得到它不用暴力手打 往后看
然后这个方法的描述和参数说完了,下面说说他用在哪,
给一个类用运行时添加一个方法 他可以用来解决我们开发中的这个问题------“unrecognized selector sent to instance 0x7faa2a132c0”
在OC中我们调用一个方法时 有个关键字 叫 “消息机制” 就是执行 [receiver message]; 这句代码其实就是发送了一个消息 (发消息的详细过程我就不写了 感兴趣 去查),
消息里面带着你调用这个方法的名称和参数以及是哪个对象发送的消息,然后 发出消息后 如果有对应的方法响应,就执行方法,没有的话就报“unrecognized selector sent to instance 0x7faa2a132c0” ,然后就crash ,为了防止crash我们可以用class_addMethod给找不到对应方法即将crash的消息添加一个与之对应的方法来防止其因为找不到相应方法而crash
在OC中找不到对相应的实现方法时 有补救机制 即 会先调用动态决议方法 该方法解决不了问题 再调用重定向方法 都解决不了问题是 crash
动态决议方法:
- + (BOOL)resolveClassMethod:(SEL)sel OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);
- + (BOOL)resolveInstanceMethod:(SEL)sel OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);
重定向方法:
- (id)forwardingTargetForSelector:(SEL)aSelector OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);
下面上代码:给一个类的对象调用一个未实现的方法 然后用runtime 在动态决议方法中为其添加实现 防止crash
Person类
- #import "Person.h"
- #import <objc/runtime.h>
- @implementation Person
- + (BOOL)resolveInstanceMethod:(SEL)sel {
- Method exchangeM = class_getInstanceMethod([self class], @selector(eatWithPersonName:));
- class_addMethod([self class], sel, class_getMethodImplementation(self, @selector(eatWithPersonName:)),method_getTypeEncoding(exchangeM));
- return YES;
- }
- - (void)eatWithPersonName:(NSString *)name {
- NSLog(@"Person %@ start eat ",name);
- }
- @end
里面重写resolveInstanceMethod方法 给找不到实现的方法 添加实现 - (void)eatWithPersonName:(NSString *)name;
第一句
Method exchangeM = class_getInstanceMethod([self class], @selector(eatWithPersonName:));
是为下面method_getTypeEncoding(exchangeM) 做铺垫 这样就拿到了eatWithPersonName方法的type encodings 用作class_addMethod的第四个参数,就是上面我提到的不用暴力手打的获取type encodings的方法
然后调用 class_addMethod 为当前类[self class] 的sel 方法 添加实现 class_getMethodImplementation(self, @selector(eatWithPersonName:)) 这一串就是拿到方法eatWithPersonName的IMP指针 然后最后一个参数是 type encodings
然后测试
- Person *person = [[Person alloc]init];
- //调用Person未实现方法eat
- [person performSelector:@selector(eat) withObject:@"minzhe"];
运行结果:
2017-07-14 14:41:35.297 RunTimeAddMethod[1458:379458] Person minzhe start eat
好了 添加上了 这样就没有 crash
iOS用runtime给一个类动态添加方法 ---class_addMethod的更多相关文章
- ios开发runtime学习三:动态添加方法(实际应用少,面试)
#import "ViewController.h" #import "Person.h" /* 1: Runtime(动态添加方法):OC都是懒加载机制,只要 ...
- 使用runtime给类动态添加方法并调用 - class_addMethod
上手开发 iOS 一段时间后,我发现并不能只着眼于完成需求,利用闲暇之余多研究其他的开发技巧,才能在有限时间内提升自己水平.当然,“其他开发技巧”这个命题对于任何一个开发领域都感觉不找边际,而对于我来 ...
- ios开发runtime学习四:动态添加属性
#import "ViewController.h" #import "Person.h" #import "NSObject+Property.h& ...
- 给python类动态添加方法(method)
群里有人问如何做到 def foo(): pass class Bar(object): pass Bar.set_instance_method(foo) b = Bar() b.foo() 这个其 ...
- ios的runtime为什么可以动态添加方法
一句话概括 每个instance都有一个isa,这个isa,里面含有所有的方法列表,ios提供库函数增加,修改,即实现了动态添加方法
- 使用TypeDescriptor给类动态添加Attribute
给类动态添加Attribute一直是我想要解决的问题,从msdn里找了很久,到Stack Overflow看了不少文章,算是最终有了答案. 先是有这样的一段解释 Attributes are stat ...
- iOS运行时使用(动态添加方法)
1 举例 我们实现一个Person类 然后Person 其实是没得对象方法eat:的 下面调用person的eat方法 程序是会奔溃的 那么需要借助运行时动态的添加方法 Person *p = [[ ...
- python装饰器、继承、元类、mixin,四种給类动态添加类属性和方法的方式(一)
介绍装饰器.继承.元类.mixin,四种給类动态添加类属性和方法的方式 有时候需要給类添加额外的东西,有些东西很频繁,每个类都需要,如果不想反复的复制粘贴到每个类,可以动态添加. # coding=u ...
- 快速上手Runtime(四)之动态添加方法
如果一个类方法非常多,加载类到内存的时候也比较耗费资源,可以使用动态给某个类,添加方法解决.做到优化内存,节省资源的效果. // // Person.m // ResolveInstanceMetho ...
- php里面用魔术方法和匿名函数闭包函数动态的给类里面添加方法
1.认识 __set (在给不可访问属性赋值时,__set() 会被调用) 也就是说你再访问一个类里面没有的属性,会出发这个方法 class A{ private $aa = '11'; publ ...
随机推荐
- linux安装oracle客户端
下载客户端软件 客户端下载地址 链接:https://pan.baidu.com/s/1StXjSjQ_6wRuwj4tewRlaA 提取码:8ynu sqlldr工具 链接:https://pan. ...
- random随机数模块
#wuyanfengimport random'''random.random()#随机数0到1的浮点数模块random.randint(1,7)#随机1到7闭区间的整数random.randrang ...
- 快速傅里叶变换详解(FFT)
自己也看了几篇博客,但是对我这种不擅长推导小白来说还是有一点困难,所以自己也写一篇博客也为像我一样的小白提供思路.以下内容包含各种LaTeX渲染,如果哪里有错误欢迎大家评论留言,或者添加本人qq:14 ...
- List集合拆分为多个List
List切分为多个List 使用SubList实现分批处理 // 创建模拟list List<Integer> dataList = new ArrayList<>(); fo ...
- 掌控安全学院SQL注入靶场
注入的本质:用户输入的字符被带入数据库中并且执行了 靶场地址:http://inject2.lab.aqlab.cn/ 第六关:http://inject2.lab.aqlab.cn/Pass-06/ ...
- pg到达梦数据迁移常见问题
1 迁移提示 ERROR: column t1.tgconstrname does not exist Position: 113 重新迁移,选择转换的时候提示:ERROR: column t1.t ...
- 字符串内特殊字符的替换处理,如对\n的替换
一.对于字符串特殊字符的替换 对于字符串内,\n的处理,如何去掉 s='123,456\n' s1=s.strip('\n') s2=s.replace('\n','') print(s) print ...
- 5.mysql的explain的分析
执行分析: 1.id 含义:表示查询的子句或者操作表的顺序 三种情况:id 相同,执行的顺序由上到下: id不同,id越大优先级越高,越先执行: id相同不相同同时存在: 2.select_type ...
- js array map
var user = ['Alice', 'Emily', 'Kate']; console.log(user); var keys = user.keys(); for ( ...
- pip python的包成功,但是import的时候报错
今天,一位同学线上反馈import python包失败了,同时附带两张图: 图1.报错代码 图2.报错提示 结合上面两个图片,我们发现这个同学import全部失败,初步怀疑该同学的本地环境上没有num ...