2011-02-03 51 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]; 
相關問題