如何将值传递给@protocol

时间:2011-07-20 12:39:43

标签: objective-c ios cocoa-touch delegates protocols

我正在尝试实施协议。

我查看了文档here,我理解了这些概念,但我认为我缺少一些东西。

我正在尝试查看用户点击表视图中的文件名,触发'didSelectRowAtIndexPath',然后通知委托用户已选择文件(在委托中触发didSelectFileName)并传递文件名。我已宣布协议如下;

@protocol FileList <NSObject>
- (void)didSelectFileName:(NSString *)fileName;    
@end

我的问题是:

  • 如何设置'fileName'值,以便在调用'didSelectFileName'时,其中包含当前值
  • 如何告诉我的代码在委托中触发'didSelectFileName'。

2 个答案:

答案 0 :(得分:3)

您不能只是向协议发送消息(也不能设置值)。您将消息发送到符合协议的类。


当您说某个类符合协议(@interface MyClass : NSObject <MyProtocol> { etc)时,您可以使用符合协议中方法的选择器安全地向该类发送任何消息。

因此,如果我们以您的协议为例,我们可以拥有一个可以向委托发送消息的类:

@interface MyClass : NSObject {
  id<FileList> _delegate;
}

@end

@implementation MyClass

- someMethod {
  NSString *fn = @"Hello.";
  [_delegate didSelectFileName:fn];
}

@end

只需确保在委派中实现协议中的方法。

您无需在委托类的界面中重新定义方法。


以下是一些关于协议的好读物:

答案 1 :(得分:1)

//在表格查看方法

- (void)tableView didSelectRowAtIndexPath....... {
UITableViewCell *cell = [tableView methodToGetCell];
if(delegate && [delegate respondsToSelector:@selector(didSelectFileName:)]){
[delegate didSelectFileName:cell.text];
}