选择器是发送消息的机制,通过 @selector(方法名)或者 创建SEL 类型的变量来调用执行方法。
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px 'Heiti SC Light'; color: #008400}p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo}p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; min-height: 13.0px}p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #78492a}p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #008400}p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #3d1d81}span.s1 {font: 11.0px Menlo; font-variant-ligatures: no-common-ligatures}span.s2 {font-variant-ligatures: no-common-ligatures}span.s3 {font-variant-ligatures: no-common-ligatures; color: #bb2ca2}span.s4 {font-variant-ligatures: no-common-ligatures; color: #4f8187}span.s5 {font-variant-ligatures: no-common-ligatures; color: #3d1d81}span.s6 {font-variant-ligatures: no-common-ligatures; color: #d12f1b}span.s7 {font-variant-ligatures: no-common-ligatures; color: #008400}span.s8 {font: 11.0px 'Heiti SC Light'; font-variant-ligatures: no-common-ligatures; color: #008400}span.s9 {font: 11.0px 'Heiti SC Light'; font-variant-ligatures: no-common-ligatures; color: #d12f1b}span.s10 {font-variant-ligatures: no-common-ligatures; color: #000000}span.s11 {font: 11.0px 'Heiti SC Light'; font-variant-ligatures: no-common-ligatures}span.s12 {font-variant-ligatures: no-common-ligatures; color: #703daa}span.s13 {font-variant-ligatures: no-common-ligatures; color: #272ad8}span.s14 {font-variant-ligatures: no-common-ligatures; color: #31595d}
//通过方法名创建选择器
SEL sel=@selector(dogEat);
Dog *xiaobai = [[Dog alloc]init];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks" //告诉编译器不会造成内存泄漏
if ([xiaobai respondsToSelector:sel]){ //判断对象所属类是否实现了selector中的方法
NSLog(@"方法1");
[xiaobai performSelector:sel]; //通过performSelector关键字,执行了选择器中的方法。
}
//用方法名对的字符串对象生成选择器
SEL sel2=NSSelectorFromString(@"dogBark:");
if ([xiaobai respondsToSelector:sel2]){
NSLog(@"方法2");
[xiaobai performSelector:sel2 withObject:[NSNumber numberWithInt:5]];
}
//用方法名的c语言字符串生成选择器
SEL sel3 = sel_getUid("dogBark:");
if ([xiaobai respondsToSelector:sel3]) {
NSLog(@"方法3");
[xiaobai dogBark:[NSNumber numberWithInt:4]];
}
//获取选择器中的方法名
NSLog(@"name = %@", NSStringFromSelector(sel)); //方法名字符串对象
NSLog(@"name = %s", sel_getName(sel2));