i have a general question about properties and ivars.
ive seen many different examples to use properties and it confuses me a bit.
method 1 only using a property without a corresponding ivar.
@property (...) Type *name;
@synthesize name;
method 2 using a property and an ivar
@interface{
Type *ivarName;
}
@property (...) Type *name;
@synthesize name = ivarName;
method 3 ignoring properties and working with ivars
@interface{
Type *ivarName;
}
ivar = ...;
i currently use method 1 for most things i do, it just works. but i have startet to wonder if i might be missing something here. i have read a lot of questions about ivars VS properties, but none of them seemed to really care about how they work together.
in most sample projects i’ve seen method 2 is used. so my question is: is there any advantage in defining a property and an ivar, and then assign the property to the ivar, than just having a property?
is the solution as simple as: only with a property can an ivar be set from ‘outside’?
i have read: Must every ivar be a property? and Property vs. ivar in times of ARC but was not able to draw a final conclusion.
Essentially, yes. Ivars in Obj-C are (by default) “protected”, meaning that the compiler won’t allow you to access them externally to the object’s own code. For example, given the following class declaration:
You might think you’d be able to access the ivar after creating the object, but trying results in an error:
That’s why ObjC uses accessor methods. Defining them manually was mandatory before the advent of declared properties:
Now, using the
@propertyand@synthesizedirectives creates those accessor methods for you (as well as the variable itself). (The manual memory management in the setter is of course also obsolete under ARC.)It is possible to make an ivar that’s accessible from outside the object:
but this isn’t considered good Objective-C style.
The Objective-C Programming Language doc contains a “Historical Note” about this:
This is a pretty big change (I was actually surprised that there’s no syntax given for ivars declared in
@interfaceanymore in that doc), but it’s definitely for the better. You should use declared properties; they do the right thing and make your code cleaner and safer.