萬能跳轉界面,完美的解耦方案
目標:
1.我們不想import這個控制的名字,然后push到一個新的界面,
2.我們想通過一個字符串跳轉到一個新的頁面,
3.服務端下發一個頁面的名字,我們可以正常跳轉
收益:
1.實現靈活跳轉
2.服務端控制
3.控制器解耦,業務解耦
實現方式:
/**
* 跳轉界面
* @param name 控制器名
* @param params 參數
*/
- (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];
}
/**
* 檢測對象是否存在該屬性
*/
- (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;
}