iOS 大纲-细节应用:定义协议、委托



在 XCode 4.3.2 的主从应用程序模板(使用 ARC、情节提要(中,我正在尝试在选择主表视图中的项目时更改(更具体地替换(详细信息视图。我正在尝试为此实现代表/协议。

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

让详细视图实现协议方法对我来说

很有意义,因为我将根据选择(通过协议方法作为字符串从主节点传递(在详细视图中推送/弹出视图控制器。

这是我尝试过的

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
}

在此过程中,在选择主表中的行时,没有任何反应。没有崩溃,没有日志显示,构建时也没有错误。我在这里错过了什么?

您需要设置 delegate 属性 - 目前它将为 nil,因此当您向其发送消息时不会发生任何事情。在 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;
}  

最新更新