减少UIViewController切换的耦合

我们一般切换UIViewController的时候用的是例如以下代码

#import "UIViewControllerDemo.h"


UIViewControllerDemo *vc = [UIViewControllerDemo alloc] initWithNibName:nil bundle:nil] autorelease];
[self.navigationController pushViewController:vc animated:YES];

当我们须要切换的UIViewController多的时候呢,代码难免写成:

#import "UIViewControllerDemo1.h"
 #import "UIViewControllerDemo2.h"
 #import "UIViewControllerDemo3.h"
 #import "UIViewControllerDemo4.h"

 UIViewControllerDemo1 *vc1
 UIViewControllerDemo2 *vc2
 UIViewControllerDemo3 *vc3
 UIViewControllerDemo4 *vc4

以后维护的时候非常是麻烦
以下我们将对UIViewController切换的方法进行改造

-(void) pushVC:(NSString *)vcName{
    Class class = NSClassFromString(vcName);
    NSAssert(class != nil, @"Class 必须存在");
    UIViewController *vc = [[[NSClassFromString(vcName) alloc] init] autorelease];

    [self.navigationController pushViewController:vc animated:YES];
}

这里能够增加一个协议,使用我们指定的方法来初始化,这样能够在初始话的同一时候带入參数

@protocol XYSwitchControllerProtocol <NSObject>
-(id) initWithObject:(id)object;
@end


-(void) pushVC:(NSString *)vcName object:(id)object{
    Class class = NSClassFromString(vcName);
    NSAssert(class != nil, @"Class 必须存在");
    UIViewController *vc = nil;

    if ([class conformsToProtocol:@protocol(XYSwitchControllerProtocol)]) {
        vc = [[[NSClassFromString(vcName) alloc] initWithObject:object] autorelease];
    }else {
        vc = [[[NSClassFromString(vcName) alloc] init] autorelease];
        vc.parameters = object;
    }

    [self.navigationController pushViewController:vc animated:YES];
}

模态的方法则多个考虑个UINavigationController

-(void) modalVC:(NSString *)vcName withNavigationVC:(NSString *)nvcName object:(id)object succeed:(UIViewController_block_void)block{
    Class class = NSClassFromString(vcName);
    NSAssert(class != nil, @"Class 必须存在");

    UIViewController *vc = nil;

    if ([class conformsToProtocol:@protocol(XYSwitchControllerProtocol)]) {
        vc = [[[NSClassFromString(vcName) alloc] initWithObject:object] autorelease];
    }else {
        vc = [[[NSClassFromString(vcName) alloc] init] autorelease];
        vc.parameters = object;
    }

    UINavigationController *nvc = nil;
    if (nvcName) {
        nvc = [[[NSClassFromString(vcName) alloc] initWithRootViewController:vc] autorelease];
        [self presentViewController:nvc animated:YES completion:block];

        return;
    }

    [self presentViewController:vc animated:YES completion:block];
}

转载于:https://www.cnblogs.com/clnchanpin/p/6984199.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值