Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to use the @property keyword in objective-c?

Tags:

objective-c

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.

  • Should declare both methods and a @property or just one of them?
like image 445
user1283776 Avatar asked Feb 06 '23 06:02

user1283776


1 Answers

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

like image 194
A O Avatar answered Feb 13 '23 06:02

A O