问题
The Scenario
I have a situation where a base class called AbstractRequest
has a delegate property of type id <AbstractRequestDelegate>
declared in the header file:
@property (nonatomic, assign) id <AbstractRequestDelegate> delegate;
The abstract delegate protocol contains a few required methods, and as indicated with the word 'abstract', both the AbstractRequest
and the AbstractRequestDelegate
are intended to be subclasses/extended.
One example of this would be the subclass ConcreteRequest and extended protocol ConcreteRequestDelegates, that both add extra methods to the abstract ones. The intention is that both the abstract and concrete class methods can send messages to the single assigned delegate instance.
At a certain point in time the ConcreteRequest would like to call a method on the delegate that is defined by ConcreteRequestDelegate. Because the type of the delegate is id , the compiler will give a warning that this method might not be implemented.
ConcreteRequest.m:38: warning: property 'delegate' requires method '-delegate' to be defined - use @synthesize, @dynamic or provide a method implementation
The Problem
This warning is justified, for the property is after all typed to id <AbstractRequestDelegate>
. In order to fix this, I want to make clear to the compiler that the delegate assigned to the concrete instance must be of type id <ConcreteRequestDelegate>
. This sounded perfectly reasonable to me, so I put in a new property in the ConcreteRequest header, hoping to override the abstract one:
@property (nonatomic, assign) id <ConcreteRequestDelegate> delegate;
But this is where the compiler disagrees with me, probably with good reason. I would have thought it would give a warning for overriding a super class' property with the wrong type, but instead it just demands me to re-synthesize this new property. I don't want to go there, because then the super class' methods won't have access to the same delegate property.
The Question
Is there a way to 're-declare' the property in the concrete subclass with the added type information? Or can you spot the error in my thinking, for maybe this is a fairly common problem that I just haven't come across until now?
Cheers,
EP.
P.S. All class and protocol names appearing in this work are fictitious. Any resemblance to real class and protocol names, open source or patented, is purely coincidental.
回答1:
The warning already gave the right clue. I used @dynamic in the overriding subclass and all is good.
回答2:
Just synthesize id<ConcreteRequestDelegate>delegate
in the ConcreteRequest.m
it will work fine...It won't create any problem.
来源:https://stackoverflow.com/questions/5896085/how-to-override-a-superclass-property-with-more-specific-types