// // Dog.h // OC3_选择器 // // Created by zhangxueming on 15/6/16. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> @interface Dog : NSObject @property (copy)NSString *name; @property (assign,nonatomic)NSInteger age; - (void)bark:(NSNumber *)count; @end
// // Dog.m // OC3_选择器 // // Created by zhangxueming on 15/6/16. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import "Dog.h" @implementation Dog - (void)bark:(NSNumber *)count { NSInteger cnt = [count integerValue]; for (NSInteger i=0; i<cnt; i++) { NSLog(@"Wang wang wang ..."); } } @end
// // main.m // OC3_选择器 // // Created by zhangxueming on 15/6/16. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> #import "Dog.h" //函数指针变量 int add(int a, int b) { return a+b; } //选择器 //运行层次概念 //sel int main(int argc, const char * argv[]) { @autoreleasepool { int (*pfunc)(int, int) = add; NSLog(@"add = %d", pfunc(3,5)); Dog *xiaoBai = [[Dog alloc] init]; //[xiaoBai bark:[NSNumber numberWithInt:4]]; //1.利用@selector关键字生成选择器 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" //方法一: //SEL select = @selector(bark:); //方法二: //利用方法名的字符串对象生成选择器 SEL select = NSSelectorFromString(@"bark:"); //方法三: //利用C语言的字符串生成选择器 //SEL select = sel_getUid("bark:"); //获取选择器中保存的方法名 NSLog(@"%s", sel_getName(select)); NSLog(@"%@", NSStringFromSelector(select)); //NSLog(@"%p", select); //判断对象所在的类是否实现选择器中的方法 if([xiaoBai respondsToSelector:select]) { //执行选择器中保存的方法 //[xiaoBai performSelector:select withObject:[NSNumber numberWithInteger:10]]; [xiaoBai bark:[NSNumber numberWithInteger:10]]; } #pragma clang diagnostic pop } return 0; }
时间: 2024-10-11 17:22:56