首页 > 代码库 > 减少UIViewController切换的耦合
减少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]; }
减少UIViewController切换的耦合
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。