我在 Customer.h 文件中定义了协议,如下所示:
@class Customer;
@protocol CustomerDelegate <NSObject>
-(void) didSelectCustomer:(Customer *) customer;
@end
@interface Customer : NSObject
{
}
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *occupation;
@end
MasterViewController(左侧)调用 didSelectCustomer 方法,如下所示:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Customer *selectedCustomer = [customers objectAtIndex:[indexPath row]];
[self.delegate didSelectCustomer:selectedCustomer];
}
现在,我需要告诉 DetailViewController(右侧)做某事。DetailViewController 符合 CustomerDelegate 协议。
@interface DetailViewController : UIViewController<UISplitViewControllerDelegate,CustomerDelegate>
{
}
-(void) didSelectCustomer:(Customer *)customer
{
NSLog(@"sssdasdasdasd");
}
didSelectCustomer 方法永远不会被调用。我想我需要设置 masterViewController.delegate = self 但我不确定在哪里设置这个东西。
更新 1:
我在 DetailViewController 中添加了 MasterViewController 的实例,但它不起作用:
- (void)viewDidLoad
{
[super viewDidLoad];
MasterViewController *master = [[MasterViewController alloc] init];
master.delegate = self;
}
解决方案:
在 AppDelegate 中:
else
{
UISplitViewController *splitViewController = (UISplitViewController *) self.window.rootViewController;
splitViewController.delegate = [splitViewController.viewControllers lastObject];
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
// splitViewController.delegate = (id)navigationController.topViewController;
DetailViewController *detail =(DetailViewController *) [splitViewController.viewControllers lastObject];
UINavigationController *masterNavigationController = [splitViewController.viewControllers objectAtIndex:0];
MasterViewController *master = (MasterViewController *)masterNavigationController.topViewController;
master.delegate = detail;
}