萬(wàn)能跳轉(zhuǎn)界面吁恍,完美的解耦方案
目標(biāo):
1.我們不想import這個(gè)控制的名字,然后push到一個(gè)新的界面,
2.我們想通過(guò)一個(gè)字符串跳轉(zhuǎn)到一個(gè)新的頁(yè)面匹表,
3.服務(wù)端下發(fā)一個(gè)頁(yè)面的名字,我們可以正常跳轉(zhuǎn)
收益:
1.實(shí)現(xiàn)靈活跳轉(zhuǎn)
2.服務(wù)端控制
3.控制器解耦宣鄙,業(yè)務(wù)解耦
實(shí)現(xiàn)方式:
/**
* 跳轉(zhuǎn)界面
* @param name 控制器名
* @param params 參數(shù)
*/
- (void)pushWithControllerName:(NSString *)name params:(NSDictionary *)params {
const char *className = [name cStringUsingEncoding:NSASCIIStringEncoding];
Class newClass = objc_getClass(className);
if (!newClass) {
Class superClass = [NSObject class];
newClass = objc_allocateClassPair(superClass, className, 0);
objc_registerClassPair(newClass);
}
id instance = [[newClass alloc] init];
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([self checkPropertyWithInstance:instance propertyName:key]) {
[instance setValue:obj forKey:key];
}
}];
[self.navigationController pushViewController:instance animated:YES];
}
/**
* 檢測(cè)對(duì)象是否存在該屬性
*/
- (BOOL)checkPropertyWithInstance:(id)instance propertyName:(NSString *)propertyName {
unsigned int outCount, i;
objc_property_t * properties = class_copyPropertyList([instance class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property =properties[i];
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
if ([propertyName isEqualToString:propertyName]) {
free(properties);
return YES;
}
}
free(properties);
return NO;
}