Can an inherited @property not satisfy a <protocol> @property?
-
18-09-2020 - |
Question
I've got a protocol:
@protocol Gadget <NSObject>
@property (readonly) UIView *view;
- (void) attachViewToParent:(UIView *)parentView;
@end
And an "abstract" base class, with an implementation (as a getter, not shown) of -(UIView *)view
:
// Base functionality
@interface AbstractGadget : NSObject {
UIView *view;
}
@property (readonly) UIView *view;
@end
But when I implement the Gadget
protocol in a subclass of AbstractGadget
, like so:
// Concrete
@interface BlueGadget : AbstractGadget <Gadget> {
}
- (void) attachViewToParent:(UIView *)parentView;
@end
@implementation BlueGadget
- (void) attachViewToParent:(UIView *)parentView {
//...
}
@end
I get a compiler error telling me "warning: property 'view' requires method '-view' to be defined." I can make this go away using @dynamic
, or adding a stub method:
- (UIView *) view {
return [super view];
}
But I just want to know if I'm doing something that's not supported, something I shouldn't be doing, or if it's just a limitation / bug in the compiler?
Solution
By declaring the property as @dynamic you are telling the compiler that the property getter (and setter if required) are implemented elsewhere (potentially at runtime). This sounds like a perfectly reasonable use case to me.
See The Docs for more information.
OTHER TIPS
I also came across this exact issue. This is one of situations that @dynamic is there for.
Here is the rule for variable, property and synthesize in objective-C:
If you have a property, you must have a @synthesize or you declare @dynamic and write the getter and setter method yourself.
So, because you have a property called view, you have to declare @synthesize. That should be it. Nothing to do with @protocol, inheritance