Tim
Tim

Reputation: 5054

Using properties in Protocols and @synthesize as a shortcut to protocol implementation

Say I create a class and a protocol like this:

@protocol MyProtocol
@required
- (void) doSomething;
@end

@interface MyClass id<MyProtocol>
@property int aNumber;
@end

@implementation MyClass
@synthesize aNumber = aNumber_;
- (void) doSomething { aNumber_++; }
@end

I can obviously pass instances of MyClass around by treating them as id<MyProtocol>s. I can't access aNumber though, if I'm dealing with something declared as id<MyProtocol>. That's expected.

I needed to do this recently. I wanted to keep using the protocol to refer to instances of my class (runtime determined) but I also wanted to access the classes properties too. I found that I could do this:

@protocol MyProtocol
@required
- (void) doSomething;
- (int) aNumber;
@end

And now anywhere I have an instance of an id<MyProtocol> I can also call [instance aNumber], without having to code up accessors directly - the synthesise call effectively implements that part of protocol for me. I could also add the setter as well, if I like.

Have I stumbled upon an intentional feature, or is this sort of thing a Bad Idea which will end up causing me problems down the line?

Thanks

Upvotes: 1

Views: 1041

Answers (1)

CRD
CRD

Reputation: 53000

Completely intentional.

When you write:

@property int aNumber;

this is really just shorthand for:

- (int) aNumber;
- (void) setaNumber:(int)value;

and the dot notation, object.property, is just shorthand for calling one of these two methods (depending on whether you are reading from, or assigning to, the property).

The @synthesize statement just writes the two methods for you.

Upvotes: 5

Related Questions