1

In the master-detail application template (using ARC, storyboards) in XCode 4.3.2, I am trying to change (more specifically replace) the detail view when an item in master table view is selected. 我正在尝试为此实现委托/协议。

我感到困惑的是 - 哪个类应该实现协议中定义的方法 - 主控还是细节?

让详细视图实现协议方法对我来说很有意义,因为我将根据选择在详细视图中推送/弹出视图控制器(通过协议方法作为字符串从 master 传递)。

这是我尝试过的

1) 在 MasterViewController.h 中定义协议

@protocol MasterViewDelegate <NSObject>
- (void)masterSelectionChanged:(NSString *)selection;
@end
@interface MasterViewController:UIViewContoller
@property (nonatomic, weak) id <MasterViewDelegate> delegate

2) 在 MasterViewController.m

@synthesize delegate;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [delegate masterSelectionChanged:@"Some string based on indexPath.row"];
}

3) 在 DetailViewController.h

#import "MasterViewController.m"
@interface DetailViewController:UINavigationController <MasterViewDelegate>
@end

4) 在 DetailViewController.m

#pragma mark - MasterViewDelegate
- (void)masterSelectionChanged:(NSString *)selection
{
    NSLog(@"the selection is: %s", selection);
    // WIll push/pop view over here, may be perform segues based on selection
}

在这个过程中,在选择主表中的行时,什么都没有发生。没有崩溃,没有日志显示,构建时也没有错误。我在这里错过了什么?

4

1 回答 1

0

您需要设置委托属性 - 目前它将为零,因此当您向其发送消息时不会发生任何事情。在 iPad 模板中,您可以在viewDidLoad详细视图控制器中执行以下操作:

[super viewDidLoad];
if (self.splitViewController) // Means this won't be called if you use this code on iPhone too.
{
    // According to comments your master controller is embedded in a nav controller
    UINavigationController *nav = (UINavigationController*)[self.splitViewController.viewControllers objectAtIndex:0];
    // I am assuming it is the root view controller
    MasterViewController *master = (MasterViewController*)nav.rootViewController;
    // Finally set the delegate
    master.delegate = self;
}  
于 2012-05-08T10:57:10.693 回答