黑马程序员技术交流社区
标题:
SEL疑问
[打印本页]
作者:
foolishlovepig
时间:
2016-1-10 14:07
标题:
SEL疑问
SEL就是方法名类型(可以理解为一种数据类型);
它将方法名转换为一种SEL数据类型,
格式:@selector (方法名)
例如:SEL s1;
s1 = @selector (test);
[p performSelector:s1];
有了方法地址,可不可以把方法地址直接作为参数传给其他的对象(类对象或者实力对象)进行使用;
作者:
香草芭芙
时间:
2016-1-10 17:28
#import "Dog.h"
#import "Person.h"
#import <Foundation/Foundation.h>
int sum(int x, int y) {
return x + y;
}
int (*func3)(int, int);
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person * p = [[Person alloc] init];
Dog * dog = [[Dog alloc] init];
SEL s1 = NSSelectorFromString(@"run"); //人的方法
SEL s2 = NSSelectorFromString(@"eat"); //狗的方法
IMP imp1 = [p methodForSelector:s1]; //<---使用p对象找到函数地址.
IMP imp2 = [dog methodForSelector:s2];
void (*func1)(id, SEL) = (void *)imp1; // <---这个才是函数指针
void (*func2)(id, SEL) = (void *)imp2;
func1(dog, s1); //即便是狗也能调用 人的方法...
func2(p, s2); //参数是 id,SEL
//
func3 = sum;
int result = func3(2, 3);
printf("%d\n", result);
}
return 0;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2