Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a 'delegate' property support multiple protocols?

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.

like image 904
Diziet Avatar asked Sep 01 '26 10:09

Diziet


1 Answers

You can create a protocol that incorporates other protocols, for example:

@protocol MyDataSourceProtocol <UITableViewDataSource, CustomControllerSearchDelegate>
@end

From the Objective-C Programming Guide:

One protocol can incorporate other protocols using the same syntax that classes use to adopt a protocol:

@protocol ProtocolName < protocol list >

Your dataSource property would then be defined as:

@property (strong) id <MyDataSourceProtocol> dataSource;

Alternatively your CustomControllerSearchDelegate protocol can incorporate the UITableViewDataSource protocol:

@protocol CustomControllerSearchDelegate <UITableViewDataSource>
  ... new methods here ...
@end

In this case, your dataSource property would then be defined as:

@property (strong) id <CustomControllerSearchDelegate> dataSource;

I personally prefer the latter approach.

like image 145
trojanfoe Avatar answered Sep 04 '26 18:09

trojanfoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!