Runtime学习小结
感觉最近记忆越来越差,所以记录一下自己学习的东西
本文用于自己学习记录,文章参考http://www.cocoachina.com/ios/20160523/16386.html
他的git:https://github.com/daiweiping/RuntimeLearn
什么是runtime,object-c是一门动态语言,需要一个运行时系统,这就是runtime系统。
object_msgSend
在objec-c中的方法调用,不是简单的方法调用,而是消息发送,也就是说它的[receiver message]会被编译器转化为:objc_msgSend(receiver,selector)。
1,object_msgSend的使用
TestClass *objct = [[TestClass alloc] init];
((void(*) (id,SEL))objc_msgSend) (objct,sel_registerName("showAge"));
((void(*) (id,SEL,NSString*))objc_msgSend) (objct,sel_registerName("showName:"),@"Dave Ping");
((void(*) (id,SEL,float,float))objc_msgSend) (objct,sel_registerName("showSizeWithWidth:andHeight:"),110.5f,200.0f);
floatf = ((float(*) (id,SEL))objc_msgSend_fpret) (objct,sel_registerName("getHeight"));
NSLog(@"height is %.2f",f);
NSString *info = ((NSString* (*) (id, SEL)) objc_msgSend) (objct, sel_registerName("getInfo"));
2动态方法解析
如果当前对象调用了一个不存在的方法Runtime会调用resolveInstanceMethod:来进行动态方法解析我们需要用class_addMethod函数完成向特定类添加特定方法实现的操作返回NO,则进入下一步forwardingTargetForSelector:
#if0
return NO;
#else
class_addMethod(self, sel, class_getMethodImplementation(self, sel_registerName("jump")), "v@1:");
return [super resolveInstanceMethod:sel];
#endif
在消息转发机制执行前,Runtime 系统会再给我们一次重定向的机会通过重载forwardingTargetForSelector:方法来替换消息的接受者为其他对象返回nil则进步下一步forwardInvocation:
-(NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector{
获取方法签名进入下一步,进行消息转发
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
-(void)forwardInvocation:(NSInvocation*)anInvocation{
消息转发
return[anInvocationinvokeWithTarget:[[Birdalloc]init]];
}
3.其他
3.1给category添加属性
3.2字典与模型互换
3.3自动归档