4

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?

Sophistifunk
  • 4,742
  • 4
  • 28
  • 37

3 Answers3

5

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.

Alan Rogers
  • 15,018
  • 3
  • 28
  • 19
2

I also came across this exact issue. This is one of situations that @dynamic is there for.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
0

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

vodkhang
  • 18,639
  • 11
  • 76
  • 110
  • Sorry, I should've been more specific. There's a complete implementation of "-(UIView *) view" in AbstractGadget. – Sophistifunk Jul 21 '10 at 02:14
  • Can you show me your code in AbstractGadget implementation as well. Something goes wrong now, because it usually works for me – vodkhang Jul 21 '10 at 03:28
  • 2
    Since the property is implemented in the base class you use @dynamic in the subclass. – JeremyP Jul 21 '10 at 09:29