Reputation: 21814
Say that I have the following public methods on my class:
- (BOOL)finished
{
return _finished;
}
- (void)setFinished:(BOOL)aValue
{
_finished = aValue;
}
Do I also need to set finished as a property on the class:
@property SomeClass *finished;
I may have misunderstood @property
, but to me it seems like I am repeating myself.
@property
or just one of them?Upvotes: 5
Views: 453
Reputation: 16660
Even there is an accepted answer, I think some information and clarification has to be added.
A. @property
does not synthesize anything. It is a method declaration. Period. This is the reason why it is allowed in protocols. (Method implementations are not allowed, not even possible in protocols.)
What let people think that is the fact, that if you do not implement alls required accessors manually, the compiler implicitly assumes a @synthesize
in the implementation and that synthesized the accessors.
But, yes, an implicit or explicit @synthesize
requires @property
. (But not the other way round!)
B. Using @property
you have to declare an ivar, too, if you explicitly define the required accessors. This is, because the implicit synthesize is "turned-off" in such a case (for good reasons).
C. Beside convenience there is a real advantage of @property
: It adds semantic information to the property. Beside bundling getter and setter (what is the getter for -setFinished:
? -isFinished
? -finished
) it holds information about copying and reference strength (weak
, strong
, copy
). Atomicity is less important, because in most cases atomicity of access does not help to solve problems of concurrent execution.
Upvotes: 2
Reputation: 5698
By declaring a @property
, the LLVM compiler will automatically "synthesize" your accessor methods (getter and setter), as well as an instance variable (ivar
), denoted by an underscore prefix (_finished
, for example)
In your case there, because you aren't doing anything special with your accessors (you are just directly reading/writing to the backing ivar
), simply declaring a @property
will do the trick. You won't need to write the -finished
and -setFinished
methods
If you do not declare @property
, you'll have to declare your ivar
@property
also indicates you are working with a member variable of an object, and as user @Sulthan says in the comment, each class holds a list of @properties
that can be searched
And another good point by the same user, @property
makes your accessor methods atomic
, which protects your ivar
from being read while it's being written
Upvotes: 6