简体   繁体   中英

two view controllers and reusability with delegate

Newbie question about design patterns in objC. I'm writing a functionality for my iphone app which I plan to use in other apps too. The functionality is written over two classes - Viewcontroller1 and Viewcontroller2. Viewcontroller1 is the root view of a navigation controller and it can push Viewcontroller2. Rest of the app will use only ViewController1 and will never access Viewcontroller2 directly. However, triggered by user events, Viewcontroller2 has to send a message to the rest of the app. My question is what is the best way of achieving it?

Currently, I use two level of delegation to send the message out from Viewcontroller2. First send it to Viewcontroller1 and then let Viewcontroller1 send it to rest of the app or the application delegate. So my code looks like -

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

I would say the implementation is fine, but this isn't necessarily a case where you should add another level of abstraction to get reusability, because it's just a general and recommended way to pass messages around objects, ie "delegation" Apple's documentation on delegation .

Also, regarding your problem case where you have to send a message "to the rest of the app" , you should consider notifications, they may be very time-saving in some situations. ( Apple's documentation on notifications , SO Question about Delegation vs Notifications )

That's the proper way of doing things ! If all your delegate method are to be invoked on viewController2, you could have only one protocol and directly assigned the delegate from viewController1 to viewControler2 but it will block you the first time tou need to invoke the delegate from viewControler1.. bad design then !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM