選擇器是發(fā)送消息的機制决瞳,通過 @selector(方法名)或者 創(chuàng)建SEL 類型的變量來調(diào)用執(zhí)行方法淑翼。
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}
//通過方法名創(chuàng)建選擇器
SEL sel=@selector(dogEat);
Dog *xiaobai = [[Dog alloc]init];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks" //告訴編譯器不會造成內(nèi)存泄漏
if ([xiaobai respondsToSelector:sel]){ //判斷對象所屬類是否實現(xiàn)了selector中的方法
NSLog(@"方法1");
[xiaobai performSelector:sel]; //通過performSelector關鍵字亚脆,執(zhí)行了選擇器中的方法乱陡。
}
//用方法名對的字符串對象生成選擇器
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));