Reputation: 38475
Quick question about semantics :)
If I was writing a protocol, which is preferred:
// (a)
@protocol MyProtocol
@property (nonatomic, copy) NSSet *things;
@end
vs.
// (b)
@protocol MyProtocol
- (NSSet *)things;
- (void)setThings:(NSSet *)things;
@end
(a) is cleaner code but has the implication that implementing classes will have an ivar for things
, which isn't the case in my project. Because of my use case, things
cannot be KVO either. It also implies that the implementing class will copy
things
, which it's not doing in every case for me.
(b) is more accurate code (it's very explicit about what you can / can't do i.e. no KVO) but it's a little messier.
Any opinions?
Upvotes: 1
Views: 81
Reputation: 112865
I am amending my answer that (a) probably is not best for a protocol but best for a non-protocol interface.
I would go with the @property
. How a property is implemented is an implementation detail and I never consider that from the outside.
Consider a v1 implementation where the property is only that. In v2 the internals are changed and either the setter or getter is made a method. Totally reasonable, one of the reasons that properties are good, they allow such changes, they hide the implementation details.
Also consider the opposite, in the next version where is is desired to remove the methods and replace them with a property. Again an implementation detail that a property in the first instance covers quite well.
Finally, in this case there is a copy
attribute which provided explicit information of how a call with a mutable object will be handled, that is lost in the method implementation.
Upvotes: 3
Reputation: 5148
Protocols define messaging contracts [1]. They are not intended to store data. According to the Apple documentation you are only supposed to add properties to class extensions (you can add properties to categories but the compiler won't synthesize an ivar) [2]. Depending on what you are trying to do I would use one of the two following approaches to be consistent with the documented usage of the Objective-C language:
If you have the source code of the class (its one you created) then use a class extension.
If you do not have the source code sub-class the object.
That being said, if you really need to do it the other way use option (b). It is more corect and more correct is cleaner code!
Here is another question that deals with the same issue.
Good luck
Upvotes: 0
Reputation: 4585
I think case 'a' makes misinformation: class adopting protocol MyProtocol can follow not rules nonatomic and copy.
And for me it's very odd add properties inside protocols. It is going against paradigms of object oriented programming: delegates shold do some action, not provide informations.
So I advice you not use 'a' and 'b' cases, but to think again about yours programm architecture.
Upvotes: 0