博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
减少UIViewController切换的耦合
阅读量:7209 次
发布时间:2019-06-29

本文共 2447 字,大约阅读时间需要 8 分钟。

我们一般切换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 
-(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

你可能感兴趣的文章
2012腾讯春季实习生面试经历(二)
查看>>
用Bootstrap框架弹出iframe页面 在弹出的模态框中载人iframe页面,bootstrapiframe
查看>>
2012腾讯暑期实习面经(技术类web前端)
查看>>
第3种方法获取redis cluster主从关系
查看>>
注册表管理(本地、远程)
查看>>
《Linux内核设计与实现》第四周读书笔记——第五章
查看>>
关于COM组件log的位置
查看>>
C++操作符重载
查看>>
postgresql 时间戳格式为5分钟、15分钟
查看>>
linq中如何在join中指定多个条件
查看>>
交换排序
查看>>
【转】链表归并排序插入排序
查看>>
EL表达式和JSTL的使用
查看>>
递归:python 实现2分查找
查看>>
Centos6.5 安装 RabbitMQ3.6.1
查看>>
如何设置eclipse自动提示功能
查看>>
mosfet详解
查看>>
hdu1203
查看>>
for_each用法
查看>>
“.NET技术”Ajax和WEB服务数据格式:自定义返回格式
查看>>