I can find plenty of questions about making objects support multiple protocols but none confirming whether a @property can. For example I have a class with a property of:
@property (strong) id dataSource;
The object passed in here supports the UITableViewDataSource protocol so I can assign it thus without problems, in ARC with no warnings:
self.tableView.dataSource = self.dataSource;
I’d like to also implement another protocol for say, searching, named CustomControllerSearchDelegate. However if I start invoking random other methods ARC unsurprisingly starts complaining. So we go down the protocol road defining it in in my object and making the property support it. This then causes problems with assigning to the table data source. So to the main question, can I do this:
@property (strong) id <UITableViewDataSource, CustomControllerSearchDelegate> dataSource;
and if not what is an appropriate alternative?
Or, what is the correct way to cast something to remove this compiler warning:
Assigning to 'id<UITableViewDataSource>' from incompatible type
'id<PickerViewControllerDataSource>'
Apologies if this is poorly explained. :/
— Edit —
So my protocol is now defined as:
@protocol PickerViewControllerDataSource <UITableViewDataSource>
With the property defined as:
@property (strong) id <PickerViewControllerDataSource> dataSource;
Yet the compiler throws the following error:
No known instance method for selector 'objectAtIndexPath:'
— Edit —
Declared above in custom protocol. Declaration now reads:
@protocol PickerViewControllerDataSource <UITableViewDataSource>
- (id)objectAtIndexPath:(NSIndexPath *)indexPath;
@optional
- (void)searchDataWithString:(NSString*)string;
- (void)cancelSearch;
@end
Thank you.
You can create a protocol that incorporates other protocols, for example:
From the Objective-C Programming Guide:
Your
dataSourceproperty would then be defined as:Alternatively your
CustomControllerSearchDelegateprotocol can incorporate theUITableViewDataSourceprotocol:In this case, your
dataSourceproperty would then be defined as:I personally prefer the latter approach.