I noticed that in some old versions of Xcode you could use properties of objects without self
just fine.
Now it gives me an error when I try to access my property without self
, but today I'm writing this code, and it works fine, and doesn't give me any errors.
[aCoder encodeObject:itemName forKey:@"itemName"];
Why is it this way? Why don't I get an error in this case? Why is an error raised in other cases? Why can't this behavior be unified, and what should I use?
You have never been able to access properties without self
. If you didn't use self
, then you were directly accessing the instance variable that had the same name as the property. This has caused endless issues for many developers.
This is why the latest compilers (in the latest versions of Xcode) generate property ivars with a leading underscore. This way, if you forget to use self
when trying to access the property, you get an error because there is no ivar with the same name.
To unify your experience you should use the following pattern with older compilers:
Define @property int foo;
. Then define ivar int _foo
. And then use @synthesize foo = _foo;
.
With newer compilers you simply declare @property int foo
and you are done. The compiler will generate the ivar int _foo
for you.
In both cases you use self.foo
for the property and _foo
to directly access the ivar.