Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between declaring an attribute and a @property in objective-c

I know that the @property generates the getters and setters in Objective-c. But I've seen some classes where they declare attributes with their respective @property and some times just the @property with no attributes and seams to work the same way. Whats the difference?

like image 333
OscarVGG Avatar asked Dec 16 '22 01:12

OscarVGG


1 Answers

I know that the @property generates the getters and setters in Objective-c.

No you don't. @property declares a property which is a getter and optionally a setter (for read/write properties). The generation of the getter and setter is done by the @synthesize in the implementation (or by you writing the getter and setter).

But I've seen some classes where they declare attributes with their respective @property

Do you mean like this?

@interface Foo : NSObject
{
    Bar* anAttribute; // <<=== this is an instance variable
}

@property (retain) Bar* anAttribute;

@end

In the modern Objective-C run time, if you @synthesize the property, you can leave out the instance variable declaration and the compiler will put it in for you. Whether you explicitly declare the instance variable or not is a matter of personal preference.


Just to confuse you a bit, in the very latest compiler, you can omit the @synthesize and the compiler will put it in for you as long as you haven't explicitly created a getter or setter.

like image 75
JeremyP Avatar answered Apr 26 '23 03:04

JeremyP