两个视图控制器和代理的可重用性

时间:2010-12-30 10:27:21

标签: iphone objective-c ios

关于objC中设计模式的新手问题。   我正在为我的iphone应用程序编写一个功能,我打算在其他应用程序中使用它。该功能写在两个类上--Viewcontroller1和Viewcontroller2。 Viewcontroller1是导航控制器的根视图,它可以推送Viewcontroller2。该应用程序的其余部分将仅使用ViewController1,并且永远不会直接访问Viewcontroller2。但是,触发了 通过用户事件,Viewcontroller2必须向其发送消息 该应用的休息。     我的问题是实现它的最佳方法是什么?

目前,我使用两级委派从Viewcontroller2发送消息。首先将其发送到Viewcontroller1,然后让Viewcontroller1将其发送到应用程序或应用程序委托的 rest 。所以我的代码看起来像 -

//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

2 个答案:

答案 0 :(得分:0)

这是正确的做事方式!如果要在viewController2上调用所有委托方法,你可以只有一个协议并直接从viewController1分配委托给viewControler2,但它会阻止你第一次需要从viewControler1调用委托。然后设计错误!< / p>

答案 1 :(得分:0)

我想说实现很好,但是这不一定是你应该添加另一个抽象级别以获得可重用性的情况,因为它只是一种通用和推荐的方式来传递对象周围的消息,即“委托”{ {3}}

此外,对于您必须向应用程序的其余部分发送消息的问题,您应该考虑通知,在某些情况下它们可能非常节省时间。 (Apple's documentation on delegationApple's documentation on notifications

相关问题