完全剪断导航栏跳转时ViewController之间的耦合

#import "FirstViewController.h"

FirstViewController *controller = [[FirstViewController alloc] init]; 
[self.navigationController pushViewController:controller animated:YES];

上面这段代码是ios开发中很常见的一段代码,但是这平常无奇的代码却有一个隐患,这个隐患在随项目不断扩展会越来越严重。那就是
ViewController之间是存在耦合的,想要跳转目标ViewController,则必须引入对应的类头文件。更有甚者,在ViewController的.h文件中暴露属性和方法,简直无法直视。这次主要解决的问题就是彻底剪断ViewController之间的耦合,清理ViewController的.h文件中暴露的内容,还一个清爽的ViewController。

流程图
导航栏流程图.png
自定义全局导航栏
  • 初始化导航栏
    因为需要统一对目标ViewController初始化,增删改查等操作,需要自定义一个全局导航栏,为了方便处理,把导航栏做成单例。
// WBNavigationController.h
@interface WBNavigationController : UINavigationController
+ (instancetype)sharedInstance;
@end

// WBNavigationController.m
@interface WBNavigationController ()
// 保存所有注册的ViewController的URL与类名
@property (nonatomic, strong) NSMutableDictionary *registerVCCls;
@end

@implementation WBNavigationController
+ (instancetype)sharedInstance {
    static WBNavigationController *navigationController = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        navigationController = [[WBNavigationController alloc] init];
    });
    return navigationController;
}
  • 导航栏操作
// WBNavigationController.m

// 注册一个ViewController到导航栏
+ (void)registerWithUrl:(NSString *)url viewControllerClass:(Class)cls {
    [WBNavigationController sharedInstance].registerVCCls[url] = cls;
}
// 移除导航栏中一个ViewController的实例
+ (void)removeViewControllerWithUrl:(NSString *)url {
    NSMutableArray *viewControllers = [[WBNavigationController sharedInstance].viewControllers mutableCopy];
    UIViewController *targetVC = [[self class] findViewControllerIfExistWithUrl:url];
    if ( [viewControllers containsObject:targetVC] ) {
        [viewControllers removeObject:targetVC];
    }
    
    [WBNavigationController sharedInstance].viewControllers = viewControllers;
}
// 根据url查找ViewController的类名
+ (Class)findViewControllerClassWithUrl:(NSString *)url {

    return [WBNavigationController sharedInstance].registerVCCls[url];
}

// 导航栏中是否存在ViewController的实例
+ (BOOL)existViewControllerWithUrl:(NSString *)url {

    NSMutableArray *viewControllers = [[WBNavigationController sharedInstance].viewControllers mutableCopy];
    UIViewController *targetVC = [[self class] findViewControllerIfExistWithUrl:url];
    
    if ( [viewControllers containsObject:targetVC] ) {
        return YES;
    }
    
    return NO;
}

// 获取导航栏中的ViewController的实例
+ (UIViewController *)findViewControllerIfExistWithUrl:(NSString *)url {

    Class vcClassName = [[self class] findViewControllerClassWithUrl:url];
    for (UIViewController *vc in [WBNavigationController sharedInstance].viewControllers) {
        if ( vcClassName == vc.class ) {
            return vc;
        }
    }
    
    return nil;
}
// 取消注册
+ (void)deregisterUrl:(NSString *)url {
    
    [[WBNavigationController sharedInstance].registerVCCls removeObjectForKey:url];
}
ViewController类别

为了方便调用,给ViewController添加一个类别用于调用导航栏的操作。

  • 初始化目标ViewController
    .h头文件中暴露属性与方法无非就是传递参数,与适时的回调。为了清除这些,给每个目标ViewController添加参数传递与回调block。
#import "UIViewController+URL.h"

@interface UIViewController (URL)
// 给目标ViewController传递的参数
@property (nonatomic, strong) id             wb_params;
// 给目标ViewController的回调
@property (nonatomic, copy) WBReplyAction    wb_replyAction; 

// 初始化目标ViewController
- (instancetype)initWithParams:(id)params;
- (instancetype)initWithParams:(id)params replyAction:(WBReplyAction)replyAction;
  • 封装导航栏操作
    封装导航栏常用操作,push,pop,以及目标ViewController的present&&dismiss操作。以下以push为例。
#import "UIViewController+URL.h"
// push操作
- (void)wb_pushViewController:(WBParams)params;
- (void)wb_pushSimpleViewController:(NSString *)url;

- (void)wb_popViewController;
- (void)wb_popViewControllerAnimate:(BOOL)animated;
- (void)wb_popToRootViewControllerAnimated:(BOOL)animated;
- (void)wb_popToViewControllerWithUrl:(NSString *)url animated:(BOOL)animated;

- (void)wb_presentViewController:(WBParams)params;
- (void)wb_presentSimpleViewController:(NSString *)url;

- (void)wb_dismissSimpleViewController;
- (void)wb_dismissViewControllerAnimated:(BOOL)animated completion:(WBCompleteAction)completion;

#import "UIViewController+URL.m"

- (void)wb_pushSimpleViewController:(NSString *)url {

    [self wb_pushViewController:^(WBNode *node) {
        node.url = url;
    }];
}

- (void)wb_pushViewController:(WBParams)params {

    WBNode *node = [self setupNode:params];

    Class vcClass = [WBNavigationController findViewControllerClassWithUrl:node.url];
    if ( !vcClass ) {
        NSLog(@"URL:%@ not register", node.url);
    }
    UIViewController *controller = [[vcClass alloc] initWithParams:node.params replyAction:node.replyAction];
    
    [[WBNavigationController sharedInstance] pushViewController:controller animated:node.animate];
}
  • 测试调用
  1. 在AppDelegate设置window的rootViewController为全局导航栏。
FirstViewController *rootViewController = [[FirstViewController alloc] init];
[[WBNavigationController sharedInstance] pushViewController:rootViewController animated:NO];

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [WBNavigationController sharedInstance];
[self.window makeKeyAndVisible];

2.注册ViewController到全局导航栏。

// 定义快速注册viewcontroller的宏
#undef  WB_IMPLEMENT_LOAD
#define WB_IMPLEMENT_LOAD( url ) \
+ (void)load { \
@autoreleasepool { \
    [WBNavigationController registerWithUrl:url viewControllerClass:[self class]]; \
} \
}

#import "SecondViewController.h"
// 注册
@implementation SecondViewController
WB_IMPLEMENT_LOAD(URL_SECOND_VC)

3.跳转调用

#import "FirstViewController.h" // 不需要引用目标ViewController,此处是主调方的。
// 简单调用,不需要传递参数与回调
[self wb_pushSimpleViewController: URL_SECOND_VC];

// 完全调用
[self wb_pushViewController:^(WBNode *node) {
      node.url = URL_SECOND_VC;
//      node.animate = NO;
      node.params = @{@"params": @"push data"};// 参数传递
      node.replyAction = ^(id result) {  // 回调
            NSLog(@"result >> %@", result[@"result"]);
        };
}];

#import "SecondViewController.h"
// 获取从前页面传递来的参数
if( self.wb_params ) NSLog(@"push get params >> %@", self.wb_params[@"params"]);

// 触发前页面的回调
if ( self.wb_replyAction ) {
        self.wb_replyAction(@{@"result": @"pop return data"});
    }

至此已完成了解决UIViewController之间的耦合问题。现在我们来对比一下前后代码对照:

#import "FirstViewController.h"

// 优化前
FirstViewController *controller = [[FirstViewController alloc] init]; 
[self.navigationController pushViewController:controller animated:YES];

// 优化后
[self wb_pushSimpleViewController: URL_FIRST_VC];

// 优化后所有ViewController的头文件应该都是这样,清爽无比。
@interface FirstViewController : UIViewController

@end

以上因为跳转ViewController间已不存在任何依赖,调用简洁清晰,更有利于项目的模块化。demo已上传至github,有任何错误与建议可以评论指出。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,544评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,596评论 4 59
  • 今天晚上去练了散打 教练也过来教了 感觉不错 还得按制饮食习惯 晚安加油 今天的六十分吧
    4c5ea9dd0572阅读 82评论 0 0
  • 商业模式的威力 对“商业模式”的定义不一而足,但多数人都会认同商业模式描述的是公司如何创造和获取价值。商业模式的各...
    水水at创投圈阅读 743评论 0 0
  • 大学是什么?每个人的看法不一样,有的人把大学当作安乐窝无忧无虑,有的人把大学看作是荒废自己埋没青春的地方。 在没有...
    16aa5fab5f62阅读 96评论 0 0