2011-02-03 52 views
3

我使用NavigationController从应用程序的rootView中“推送”viewControllers。Delegate和NavigationController的问题

我想使用委托来交流当前加载的视图和rootViewController。我能够使用NSNotificationCenter来做到这一点,但是想要为这种特殊情况进行尝试,因为通信总是一对一的。

在该被推视图,我声明在头文件下列代表protocole:

#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 

的doAction IBAction为被连接到一个UIButton在视图中。我在执行文件,我说:

#import "AnotherViewController.h"  
@implementation AnotherViewController 

@synthesize delegate; 

- (IBAction) doAction { 
    NSLog(@"doAction"); 
    [self.delegate doDelegatedAction:self]; 
} 

在我RootViewController.h我加AnotherViewControllerDelegate的接口声明:

@interface RootViewController : UIViewController <AnotherViewControllerDelegate> {... 

,这对我的实现文件

- (void) doDelegatedAction:(AnotherViewController *)controller { 
    NSLog(@"rootviewcontroller->doDelegatedAction"); 
} 

不幸的是它不工作。未调用rootViewController中的doDelegatedAction。我怀疑这是因为我的方式推AnotherViewController:

AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil]; 
    [self.navigationController pushViewController:detailViewController animated:YES]; 
    [detailViewController release]; 

我应该告诉,以任何方式,以AnotherViewController其委托将是RootViewController的只是在那一刻,它已经被推?还是我缺少别的东西?

+0

你在哪里赋值的`delegate`?你必须告诉`AnotherViewController`的实例,`RootViewController`的哪个实例是它的委托。 – 2011-02-03 18:06:39

回答

1

您需要将delegateAnotherViewController设置为rootViewController,以便正确连接所有设备。

如果要初始化在AnotherViewControllerrootViewController这将是:

AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil]; 
detailViewController.delegate = self; 
[self.navigationController pushViewController:detailViewController animated:YES]; 
相关问题