【发布时间】:2011-02-03 18:02:29
【问题描述】:
我正在使用 NavigationController 从应用的 rootView 中“推送”视图控制器。
我想使用委托来通信当前加载的视图和 rootViewController。我可以使用 NSNotificationCenter 做到这一点,但想尝试一下这种特殊情况下的代表,因为沟通总是一对一的。
在推送的视图中,我在头文件中声明了以下委托协议:
#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?还是我错过了什么?
【问题讨论】:
-
你在哪里给
delegate赋值?你必须告诉AnotherViewController的实例RootViewController的哪个实例是它的委托。
标签: iphone objective-c xcode ios4 delegates