Whats the differences between self->_var and simple _var?

152 Views Asked by At

So if I have in iOS (with Objective C, not sure if this the same for Swift) e.g.

@property (nonatomic, copy) NSString *aString;

And then some where in the code I have

// Simple ivar access in some method
_aString = anyStringOrNil;

// Self-> ivar access in some other method
self->_aString = anyStringOrNil;

I would like to know the differences between using one or the other

1

There are 1 best solutions below

2
Simon Goldeen On

As you posted, those are identical. There is a difference between directly accessing the ivar and going through a property however. If you set the string as so:

self.aString = someString;

That would go through the automatically generated setter which, based on your property declaration would make a copy of someString. This is preferable in the case of working with mutable strings. You don't want the string to change out from under you. In both examples that you used, you are directly setting the value of _aString to the string reference, so if the string is a mutable string that is owned by someone else, it could change without warning and lead to unexpected results.

It is generally better practice to go through the setter (self.property = foo) rather than directly accessing the ivar as it is possible that the setter for the property has some behavior you may want and directly accessing it bypasses this. Of course, there are situations where accessing the ivar directly is required, but it is best to go through the property as a default.