[英]two view controllers and reusability with delegate
关于objC中的设计模式的新手问题。 我正在为我的iPhone应用程序编写一项功能,该功能也计划在其他应用程序中使用。 该功能是通过两个类(Viewcontroller1和Viewcontroller2)编写的。 Viewcontroller1是导航控制器的根视图,它可以推送Viewcontroller2。 该应用程序的其余部分将仅使用ViewController1,并且永远不会直接访问Viewcontroller2。 但是,由于用户事件的触发,Viewcontroller2必须向应用程序的其余部分发送一条消息。 我的问题是实现它的最佳方法是什么?
当前,我使用两个级别的委派从Viewcontroller2发送消息。 首先将其发送到Viewcontroller1,然后让Viewcontroller1将其发送到应用程序的其余部分或应用程序委托。 所以我的代码看起来像-
//Viewcontroller1.h
@protocol bellDelegate
-(int)bellRang:(int)size;
@end
@interface Viewcontroller1 : UITableViewController <dummydelegate> {
id <bellDelegate> delegate;
@end
//Viewcontroller1.m
@implementation Viewcontroller1
-(void)viewDidLoad {
//some stuff here
Viewcontroller2 *vc2 = [[Viewcontroller2 alloc] init];
vc2.delegate = self;
[self.navigationController pushViewController:vc2
animated:YES];
}
-(int)dummyBell:(int)size {
return([self.delegate bellRang:size]);
}
//Viewcontroller2.h
@protocol dummyDelegate
-(int)dummyBell:(int)size;
@end
@interface Viewcontroller2 : UITableViewController {
id <dummyDelegate> delegate;
@end
//Viewcontroller2.m
@implementation Viewcontroller2
-(int)eventFoo:(int)size {
rval = [self.delegate dummyBell:size];
}
@end
我会说实现很好,但这并不一定是您应该添加另一个抽象级别来获得可重用性的情况,因为这只是在对象周围传递消息的通用且推荐的方法,即“委托” Apple有关委托的文档 。
另外,对于您必须向“应用程序的其余部分”发送消息的问题情况,您应该考虑通知,在某些情况下通知可能非常节省时间。 ( Apple的通知文档 , 关于委托与通知的问题 )
那是做事的正确方法! 如果要在viewController2上调用所有委托方法,则可能只有一个协议,并且直接将委托从viewController1分配给viewControler2,但它会阻止您第一次需要从viewControler1调用委托。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.