在开发项目中,会有这样变态的需求:
思考:wocao!这变态的需求,要拒绝他吗?
switch判断呗,考虑所有跳转的因素?这不得写死我...
我是这么个实现的(runtime是个好东西)
利用runtime动态生成对象、属性、方法这特性,我们可以先跟服务端商量好,定义跳转规则,比如要跳转到A控制器,需要传属性id、type,那么服务端返回字典给我,里面有控制器名,两个属性名跟属性值,客户端就可以根据控制器名生成对象,再用kvc给对象赋值,这样就搞定了 ---O(∩_∩)O哈哈哈
比如:根据推送规则跳转对应界面HSFeedsViewController
HSFeedsViewController.h:
1 | @interface HSFeedsViewController : UIViewController |
4 | @property (nonatomic, copy) NSString *ID; |
6 | @property (nonatomic, copy) NSString *type; |
AppDelegate.m:
2 | NSDictionary *userInfo = @{ |
3 | @ "class" : @ "HSFeedsViewController" , |
1 | - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo |
01 | - (void)push:(NSDictionary *)params |
04 | NSString *class =[NSString stringWithFormat:@ "%@" , params[@ "class" ]]; |
05 | const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding]; |
07 | Class newClass = objc_getClass(className); |
11 | Class superClass = [NSObject class]; |
12 | newClass = objc_allocateClassPair(superClass, className, 0); |
14 | objc_registerClassPair(newClass); |
17 | id instance = [[newClass alloc] init]; |
19 | NSDictionary * propertys = params[@ "property" ]; |
20 | [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { |
22 | if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) { |
24 | [instance setValue:obj forKey:key]; |
28 | UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController; |
29 | UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex]; |
31 | [pushClassStance pushViewController:instance animated:YES]; |
01 | - (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName |
03 | unsigned int outCount, i; |
05 | objc_property_t * properties = class_copyPropertyList([instance |
07 | for (i = 0; i < outCount; i++) { |
08 | objc_property_t property =properties[i]; |
10 | NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; |
12 | if ([propertyName isEqualToString:verifyPropertyName]) { |
具体使用和代码: https://github.com/HHuiHao/Universal-Jump-ViewController