Subclass implements its own protocol delegate

351 views Asked by At

I am new to iOS, don't know if this is possible or not.

Basically I have two classes Parent and Child.

Parent has a delegate which conforms to ParentProtocol. However, the delegate in Child not only conforms to ParentProtocol, but also another ChildProtocol.

So is it possible to do the following?

@interface Parent {
  @property (nonatomic, unsafe_unretained) id<ParentProtocol> delegate;
}

@interface Child : Parent {
  @property (nonatomic, unsafe_unretained) id<ParentProtocol, ChildProtocol> delegate;
}
1

There are 1 answers

0
Nate Chandler On BEST ANSWER

Yes, this is valid code. This amounts to declaring the methods

- (id<ParentProtocol>)delegate;
- (void)setDelegate:(id<ParentProtocol>)delegate;

in the Parent interface and declaring methods for the same selectors (-delegate and -setDelegate) in the Child interface

- (id<ParentProtocol, ChildProtocol>)delegate;
- (void)setDelegate:(id<ParentProtocol, ChildProtocol>)delegate;

This is permissible (and causes no warnings) because id<ParentProtocol> and id<ParentProtocol, ChildProtocol> are compatible types. (Contrast this to the situation where in Child's declaration you declare delegate to be of type NSArray *. You'll get the warning Property type 'NSArray *' is incompatible with type 'id<ParentProtocol>' inherited from 'Parent'.)

By the way, it is worth noting that you can define ChildProtocol to inherit from ParentProtocol by writing

@protocol ParentProtocol <NSObject>
//....
@end

and

@protocol ChildProtocol <ParentProtocol>
//....
@end

Which in turn would allow you to write in the interface of Child

@property (nonatomic, unsafe_unretained) id<ChildProtocol>;

rather than

@property (nonatomic, unsafe_unretained) id<ParentProtocol, ChildProtocol>;