SEL类型概述
SEL类型代表着方法的签名,在类对象的方法列表中存储着该签名与方法代码的对应关系
每个类的方法列表都存储在类对象中
每个方法都有一个与之对应的SEL类型的对象
根据一个SEL对象就可以找到方法的地址,进而调用方法
检查对象/类中是否实现了某个方法
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
+ (void)test;
@end
@implementation Person
+ (void)test{
NSLog(@"test");
}
@end
int main(int argc, const char * argv[]) {
// 查看对象中是否存在某个方法
SEL sel1 = @selector(setAge:);
Person *p = [[Person alloc] init];
BOOL flag = [p respondsToSelector:sel1];
NSLog(@"flag --> %i", flag); // flag --> 1
// 查看类中是否存在某个方法
SEL sel2 = @selector(test);
flag = [Person respondsToSelector:sel2];
NSLog(@"flag --> %i", flag); // flag --> 1
return 0;
}
配合对象/类来调用某个SEL方法
使用performSelector调用类方法或对象方法时,最多传递2个参数,参数类型必须是对象类型
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
@property NSString *name;
+ (void)test;
+ (void)print: (NSString *)msg;
@end
@implementation Person
+ (void)test{
NSLog(@"test");
}
+ (void)print:(NSString *)msg {
NSLog(@"msg --> %@", msg);
}
@end
int main(int argc, const char * argv[]) {
// 使用performSelector调用对象需要传参数的方法,参数必须是对象类型
SEL sel1 = @selector(setName:);
Person *p = [[Person alloc] init];
[p performSelector:sel1 withObject:@"张三"];
NSLog(@"name --> %@", [p name]); // name --> 张三
// 使用performSelector调用类不需要传参数的方法
SEL sel2 = @selector(test);
[Person performSelector:sel2]; // test
// 使用performSelector调用类需要传参数的方法,参数必须是对象类型
SEL sel3 = @selector(print:);
[Person performSelector:sel3 withObject:@"hello"]; // msg --> hello
return 0;
}
配合对象将SEL类型作为方法的形参
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)makeObject:(id)obj :(SEL)sel;
@end
@implementation Person
- (void)makeObject:(id)obj :(SEL)sel {
[obj performSelector:sel];
}
@end
@interface Car : NSObject
- (void)run;
@end
@implementation Car
- (void)run {
NSLog(@"run");
}
@end
int main(int argc, const char * argv[]) {
Car *c = [Car new];
SEL sel = @selector(run);
Person *p = [Person new];
[p makeObject:c :sel]; // run
return 0;
}