【iOS 1 行代码系列】之 一行代码解耦控制器UIViewController

实现原理:

  1. NSClassFromString()
  2. KVC
  3. 新建分类,重写方法:- (void)setValue:(id)value forUndefinedKey:(NSString *)key 防止崩溃

地址:

JHUIViewControllerDecoupler: https://github.com/xjh093/JHUIViewControllerDecoupler

/// string -> controller, with some parameters.
+ (UIViewController *)jh_controllerFromString:(NSString *)string
                                     paramter:(NSDictionary *)dictionary;

集成到baseViewController:

一行代码调用完成

in base UIViewController:

/// push a specified VC
- (void)pushSpecifiedVC:(NSString *)VCString parameter:(NSDictionary *)dic{
    UIViewController *vc = [JHUIViewControllerDecoupler jh_controllerFromString:VCString paramter:dic];
    [self.navigationController pushViewController:vc animated:YES];
}

/// present a specified vc
- (void)presentSpecifiedVC:(NSString *)VCString parameter:(NSDictionary *)dic navigation:(BOOL)flag{
    UIViewController *vc = [JHUIViewControllerDecoupler jh_controllerFromString:VCString paramter:dic];
    JHBaseNavigationController *nav = nil;
    if (flag) {
        nav = [[JHBaseNavigationController alloc] initWithRootViewController:vc];
    }
    [self presentViewController:nav?nav:vc animated:YES completion:nil];
}

/// a specified VC
- (UIViewController *)specifiedVC:(NSString *)VCString parameter:(NSDictionary *)dic{
    return [JHUIViewControllerDecoupler jh_controllerFromString:VCString paramter:dic];
}

示例

控制器 B,长这样:

@interface UIViewControllerB : UIViewController
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) NSInteger age;

@property (copy, nonatomic) void (^editNameBlock)(NSString *name);
@end

由控制器 A 跳转到 控制器 B :

NSMutableDictionary *mdic = @{}.mutableCopy;

// 属性附值
[mdic setValue:@"Haocold" forKey:@"name"];
[mdic setValue:@18 forKey:@"age"];

// block 也是可以的
void (^editNameBlock)(NSString *name) = ^(NSString *name){
      // code goes here...
};
[mdic setValue:editNameBlock forKey:@"editNameBlock"];

// 跳转
[self pushSpecifiedVC:@"UIViewControllerB" parameter:mdic];

你可能感兴趣的:(【iOS 1 行代码系列】之 一行代码解耦控制器UIViewController)