iOS的反射机制就是根据字符串返回相应的class或者selector,然后你就可以做你想要做的事了,比如你抽象一个类,然后很多子类继承这个类,那么具体一个子类触发一个事件通过delegate 将类名传过来给这个抽象类,然后用另一个类导入这个抽象类,那么这么类就可以得到抽象类的具体子类属性,方法等等
我的网络框架就是这样搭建的,首先建一个抽象请求类,然后具体接口请求子类继承这个抽象类,那么只要请求子类赋值属性,就可以获取其请求参数了,然后将发请求写在一个公共的类里面,导入请求抽象类,只要某个子类触发请求,就可以获取其请求参数,这样做的好处是将请求参数和发请求分开,耦合度更低,便于维护。
好了,废话多了,那么来看看简单代码:
@interface PersonClass : NSObject
- (void) reflect;
@end
@implementation PersonClass
- (void) reflect{
NSLog(@"reflect!!!");
}
@end
// 正常调用
PersonClass *person = [[PersonClass alloc] init];
[person reflect];
//反射调用
Class cls = NSClassFromString(@"PersonClass"); //通过字符串获取其类
id person2= [[cls alloc] init];
SEL selector = NSSelectorFromString(@"PersonClass"); //通过字符串获取其方法名
[person2 performSelector:selector withObject:nil];
接下来通过runtime特性获取类的属性,并存入数组:
- (NSArray *)getPropertyList: (Class)clazz{
u_int count;
objc_property_t *properties = class_copyPropertyList(clazz, &count);
NSMutableArray *propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++){
const char* propertyName = property_getName(properties[i]);
[propertyArray addObject: [NSString stringWithUTF8String: propertyName]];
}
free(properties);
return propertyArray;
}
- (NSDictionary *)convertDictionary{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSArray *propertyList = [self getPropertyList:[PersonClass class]];
for (NSString *key in propertyList) {
SEL selector = NSSelectorFromString(key);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id value = [self performSelector:selector];
#pragma clang diagnostic pop
if (value == nil) {
value = [NSNull null];
}
[dict setObject:value forKey:key];
}
return dict;
}
将一个字典赋值给字典:
- (void)dictionaryForObject:(NSDictionary*) dict{
for (NSString *key in [dict allKeys]) {
id value = [dict objectForKey:key];
if (value==[NSNull null]) {
continue;
}
if ([value isKindOfClass:[NSDictionary class]]) {
id subObj = [self valueForKey:key];
if (subObj)
[subObj dictionaryForObject:value];
}
else{
[self setValue:value forKeyPath:key];
}
}
}