Reputation: 2650
I'm using a NavigationController to "push" viewControllers from the rootView of an app.
I want to use delegates to comunicate the currently loaded view and the rootViewController. I was able to do this using NSNotificationCenter, but want give a try to delegates for this particular situation, since the communication is always going to be one-to-one.
In the view that is pushed, I declared the following delegate protocole in the header file:
#import <UIKit/UIKit.h>
@protocol AnotherViewControllerDelegate;
@interface AnotherViewController : UIViewController {
id <AnotherViewControllerDelegate> delegate;
}
- (IBAction) doAction;
@property (nonatomic, assign) id delegate;
@end
@protocol AnotherViewControllerDelegate <NSObject>
- (void) doDelegatedAction:(AnotherViewController *)controller;
@end
The doAction IBAction is connected to a UIButton in the view. In my implementation file, I added:
#import "AnotherViewController.h"
@implementation AnotherViewController
@synthesize delegate;
- (IBAction) doAction {
NSLog(@"doAction");
[self.delegate doDelegatedAction:self];
}
In my RootViewController.h I added AnotherViewControllerDelegate to the interface declaration:
@interface RootViewController : UIViewController <AnotherViewControllerDelegate> {...
and this to my implementation file
- (void) doDelegatedAction:(AnotherViewController *)controller {
NSLog(@"rootviewcontroller->doDelegatedAction");
}
Unfortunately it's not working. doDelegatedAction in the rootViewController is not been called. I suspect it's because of the way I push the AnotherViewController:
AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
Should I tell, in any way, to AnotherViewController that its delegate is going to be RootViewController just in the moment it's been pushed? or am I missing something else?
Upvotes: 3
Views: 2574
Reputation: 6642
You need to set the delegate
of AnotherViewController
to the rootViewController
in order for everything to be connected up properly.
If you are initializing AnotherViewController
in your rootViewController
it would be:
AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil];
detailViewController.delegate = self;
[self.navigationController pushViewController:detailViewController animated:YES];
Upvotes: 1