class反射
1: 通过类名的字符串形式实例化对象
Class class = NSClassFromString(@"Student");
Student *stu = [[class alloc] init];
2:将类名变为字符串
Class class = [Student class];
NSString *className = NSStringFromClass(class);
3:SEL反射
SEL selector = NSSelectorFromString(@"setName:");
[stu performSelector:selector withObject:@"zhang"];
4:将方法变成字符串
SEL selector = NSSelectorFromString(@"setName:");
NSString *selectorName = NSStringFromSelector(selector);
NSLog(@"selectorName: %@", selectorName);
NSString *selectorName2 = NSStringFromSelector(@selector(setName:));
NSLog(@"selectorName2: %@", selectorName2);
5:去除[stu performSelector:selector withObject:@"zhang"]的警告
<1.> #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[stu performSelector:selector withObject:@"zhang"];
#pragma clang diagnostic pop
<2.> 定义一个宏
#define SuppressPerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while(0)
使用 :SuppressPerformSelectorLeakWarning([stu performSelector:selector withObject:@"zhang"]);
6:什么是SEL?如何声明一个SEL?通过哪些方法能够调用SEL包装起来的方法?
<1> SEL就是对方法的一种包装。包装的SEL类型数据它对应的方法地址,找到方法地址就可以调用方法。在内存中每个类的方法都存储在类对象中,每个方法都有一个与之对应的SEL类型的数据,根据一个SEL数据就可以找到对应的方法地址,进而调用方法。
<2> SEL s1 = @selector(test1); // 将test1方法包装成SEL对象
<3> SEL s2 = NSSelectorFromString(@"test1"); // 将一个字符串方法转换成SEL对象
<4> 调用方法有两种方式
直接通过方法名来调用[person text];
间接的通过SEL数据来调用SEL aaa = @selector(text);[person performSelector:aaa];
网友评论