2011-02-03 4 views
3

Я использую navigationController для «push» viewControllers из корневого приложения.Проблема с делегатом и NavigationController

Я хочу использовать делегатов для связи с загруженным в настоящее время представлением и корневым контроллером. Я смог сделать это с помощью 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"); 
} 

К сожалению, он не работает. doDelegatedAction в rootViewController не вызывается. Я подозреваю, что это из-за того, как я подтолкнуть AnotherViewController:

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

Должен ли я сказать, в любом случае, чтобы AnotherViewController, что его представитель будет RootViewController только в тот момент, это была нажата? или я пропущу что-то еще?

+0

Где вы присвоить значение 'delegate'? Вы должны указать экземпляр «AnotherViewController», экземпляр которого «RootViewController» является его делегатом. –

ответ

1

Необходимо установить delegate из AnotherViewController на номер rootViewController, чтобы все было правильно подключено.

Если вы инициализация AnotherViewController в вашем rootViewController было бы:

AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil]; 
detailViewController.delegate = self; 
[self.navigationController pushViewController:detailViewController animated:YES]; 
Смежные вопросы