How to override a superclass' property with more specific types?

不羁岁月 提交于 2019-11-30 13:39:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!