Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly subclass a delegate property in Objective-C?

In subclassing a class, I want to also subclass a delegate of the parent class given that the subclass now has additional functionality. What's the best way to go about doing this? If I just declare another delegate property in the subclass with the same name I would get a warning "Property type 'id' is incompatible with type 'id' inherited from 'ParentClass'

like image 506
Boon Avatar asked Mar 19 '12 04:03

Boon


People also ask

How do I set delegates in Objective-C?

An Objective-C delegate is an object that has been assigned to the delegate property another object. To create one, you define a class that implements the delegate methods you're interested in, and mark that class as implementing the delegate protocol.

How do you conform to a protocol in Objective-C?

Objective-C Language Protocols Conforming to Protocols It is also possible for a class to conform to multiple protocols, by separating them with comma. Like when conforming to a single protocol, the class must implement each required method of each protocols, and each optional method you choose to implement.

Is multiple inheritance possible in Objective-C?

In keeping with its clean and simple design, Objective C does not support multiple inheritance, though features have been developed to replace some of the functionality provided by multiple inheritance (see run-time section below). The root of the Objective C class hierarchy is the Object class.


1 Answers

Given this example that produces the warning:

// Class A
@protocol ClassADelegete;

@interface ClassA : NSObject
@property (nonatomic, weak) id<ClassADelegete> delegate;
@end

@protocol ClassADelegete <NSObject>
- (void)classADidSomethingInteresting:(ClassA *)classA;
@end

// Class B
@protocol ClassBDelegete;

@interface ClassB : ClassA
@property (nonatomic, weak) id<ClassBDelegete> delegate; // Warning here
@end

@protocol ClassBDelegete <ClassADelegete>
- (void)classBDidSomethingElse:(ClassB *)classB;
@end

Two solutions that remove the warning are.

1) In the subclass, place the protocol definition before the class definition. This is what UITableViewDelegate in UITableView.h does:

// Class B
@class ClassB;

@protocol ClassBDelegete <ClassADelegete>
- (void)classBDidSomethingElse:(ClassB *)classB;
@end

@interface ClassB : ClassA
@property (nonatomic, weak) id<ClassBDelegete> delegate;
@end

2) In the subclass, add the original protocol alongside the new one:

// Class B
@protocol ClassBDelegete;

@interface ClassB : ClassA
@property (nonatomic, weak) id<ClassADelegete, ClassBDelegete> delegate;
@end

@protocol ClassBDelegete <ClassADelegete>
- (void)classBDidSomethingElse:(ClassB *)classB;
@end

I assume (1) works as Apple do it this way, Option (2) removes the warning but I haven't compiled and run anything setup this way.

like image 75
Rory O'Bryan Avatar answered Oct 05 '22 22:10

Rory O'Bryan