'委托'属性可以支持多种协议吗?

Diz*_*iet 2 delegates protocols properties objective-c

我可以找到很多关于使对象支持多个协议但没有确认@property是否可以的问题.例如,我有一个属性为的类:

@property (strong) id dataSource;
Run Code Online (Sandbox Code Playgroud)

这里传入的对象支持UITableViewDataSource协议,所以我可以在没有问题的情况下分配它,没有警告:

self.tableView.dataSource = self.dataSource;
Run Code Online (Sandbox Code Playgroud)

我还要实现另一个协议,比如说,搜索,名为CustomControllerSearchDelegate.但是,如果我开始随机调用其他方法,ARC不出所料地开始抱怨.因此,我们沿着协议道路前进,在我的对象中定义它并使属性支持它.这会导致分配到表数据源时出现问题.那么对于主要问题,我可以这样做:

@property (strong) id <UITableViewDataSource, CustomControllerSearchDelegate> dataSource;
Run Code Online (Sandbox Code Playgroud)

如果不是什么是合适的选择?

或者,什么是强制删除此编译器警告的正确方法:

Assigning to 'id<UITableViewDataSource>' from incompatible type
'id<PickerViewControllerDataSource>'
Run Code Online (Sandbox Code Playgroud)

如果解释得不好,请道歉.:/

- 编辑 -

所以我的协议现在被定义为:

@protocol PickerViewControllerDataSource <UITableViewDataSource>
Run Code Online (Sandbox Code Playgroud)

该属性定义为:

@property (strong) id <PickerViewControllerDataSource> dataSource;
Run Code Online (Sandbox Code Playgroud)

然而,编译器抛出以下错误:

No known instance method for selector 'objectAtIndexPath:'
Run Code Online (Sandbox Code Playgroud)

- 编辑 -

以上在自定义协议中声明.宣言现为:

@protocol PickerViewControllerDataSource <UITableViewDataSource>

- (id)objectAtIndexPath:(NSIndexPath *)indexPath;

@optional

- (void)searchDataWithString:(NSString*)string;
- (void)cancelSearch;

@end
Run Code Online (Sandbox Code Playgroud)

谢谢.

tro*_*foe 5

您可以创建包含其他协议的协议,例如:

@protocol MyDataSourceProtocol <UITableViewDataSource, CustomControllerSearchDelegate>
@end
Run Code Online (Sandbox Code Playgroud)

Objective-C编程指南:

一个协议可以使用类用于采用协议的相同语法来合并其他协议:

@protocol ProtocolName <协议列表>

您的dataSource财产将被定义为:

@property (strong) id <MyDataSourceProtocol> dataSource;
Run Code Online (Sandbox Code Playgroud)

或者,您的CustomControllerSearchDelegate协议可以包含UITableViewDataSource协议:

@protocol CustomControllerSearchDelegate <UITableViewDataSource>
  ... new methods here ...
@end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的dataSource财产将被定义为:

@property (strong) id <CustomControllerSearchDelegate> dataSource;
Run Code Online (Sandbox Code Playgroud)

我个人更喜欢后一种方法.