SEL类型
说明:SEL类型第一次调用时会逐个匹配方法名,并加载到内存,后面调用时就直接在内存中查找方法
1 检查对象/方法有没有实现某个方法(使用respondsToSelector方法)
@implementation Person
-(void)setAge:(int)age{
_age=age;
}
-(int)age{
return _age;
}
@end
SEL sel=@selector(setAge:);首先将某个方法封装成SEL类型
Person *p=[[Person alloc]init];
BOOL flag=[p respondsToSelector:sel];查询某个类中是否有封装的方法,有返回true,没有返回false
NSLog(@"p falg=%i",flag);对象调用就查找-开头的方法
flag=[Person respondsToSelector:sel];
NSLog(@"Person falg=%i",flag);类调用就查找+开头的方法
运行结果:
2016-01-17 16:27:13.589 SelDemo[491:6385] p falg=1
2016-01-17 16:27:13.590 SelDemo[491:6385] Person falg=0
2 配合对象/类调用某个方法(使用performSelector方法)
@implementation Person
-(void)setAge:(int)age{
_age=age;
}
-(int)age{
return _age;
}
-(void)demo{
NSLog(@"demo方法");
}
@end
SEL sel=@selector(demo);
Person *p=[[Person alloc]init];
[p performSelector:sel];
sel=@selector(setAge:);
[ p performSelector:sel withObject:@(30)];
NSLog(@"age=%i",p.age);
运行结果:
2016-01-17 16:57:48.923 SelDemo[611:14843] demo方法
2016-01-17 16:57:48.924 SelDemo[611:14843] age=7719
特别提醒:
1 performSelector传递的参数要是对象类型,否则数据会有问题
2 performSelector最多只能传递两个参数
3 作为行参,调用指定的方法
@implementation Camera
- (void)open{
NSLog(@"打开相机");
}
@end
@implementation Person
-(void)openCamera:(id)obj andSel:(SEL)sel{
[obj performSelector:sel];
}
@end
SEL sel=@selector(open);
Camera *c=[[Camera alloc]init];
Person *p=[[Person alloc]init];
[p openCamera:c andSel:sel];
运行结果:
2016-01-17 17:22:27.137 SelDemo[696:19321] 打开相机