Search code examples
objective-ccocoaoopcocoa-design-patterns

Can an inherited @property not satisfy a <protocol> @property?


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.