1)Sense:
Teacher: Where is LiLei from?
XiaoMing: I don't know.
Teacher: Guess?.
LiHua: He is from __
在程序当中,假设XiaoMing的中没有guess这个方法,后来被Runtime添加一个名字叫guess的方法,最终再调用guess方法做出相应。那么,Runtime是如何做到的呢?
①动态给XiaoMing类中添加guess方法:
class_addMethod([self.xiaoMing class], @selector(guess), (IMP)guessAnswer, "v@:");
这里参数地方说明一下:
(IMP)guessAnswer 意思是guessAnswer的地址指针;
"v@:" 意思是,v代表无返回值void,如果是i则代表int;@代表 id sel; : 代表 SEL _cmd;
“v@:@@” 意思是,两个参数的没有返回值。
②调用guess方法响应事件:
[self.xiaoMing performSelector:@selector(guess)];
③编写guessAnswer的实现:
void guessAnswer(id self,SEL _cmd){
NSLog(@"He is from GuangTong");
}
这个有两个地方留意一下:
1.void的前面没有+、-号,因为只是C的代码。
2.必须有两个指定参数(id self,SEL _cmd)
-(void)answer{
class_addMethod([self.xiaoMing class], @selector(guess), (IMP)guessAnswer, "v@:");
if ([self.xiaoMing respondsToSelector:@selector(guess)]) {
[self.xiaoMing performSelector:@selector(guess)];
} else{
NSLog(@"Sorry,I don't know");
}
self.cityTf.text = @"GuangTong";
}
void guessAnswer(id self,SEL _cmd){
NSLog(@"He is from GuangTong");
}
网友评论