Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between self and underscore to access the property in objective c?

Tags:

ios

I am so confused between self and underscore to access the property in Objective c, whenever we create property, its getter-setter automatically generated. So we can access the same property with self.property and same as _property. In my opinion, there shoulb be some difference which i am not getting. PLease tell me with examples.

like image 699
Tinku Avatar asked Jun 17 '15 20:06

Tinku


People also ask

What does underscore mean in Objective-c?

In objective-c the convention is to use an underscore as a prefix for the instance variable name. So in your code when you call _someProperty from within an object, you are calling the instance variable directly.


3 Answers

Let's say you have a property defined as follows:

@property (nonatomic,strong) NSString* name;

The getters and setters of the name property are automatically generated for you.Now, the difference between using underscore and self is that:

self.name =@"someName"; // this uses a setter method generated for you.
_name = @"someName"; // this accesses the name property directly.

The same applies for getting the name property;

like image 135
Lehlohonolo_Isaac Avatar answered Oct 07 '22 16:10

Lehlohonolo_Isaac


The underbar (underscore) version is the actual instance variable, and should not be referenced directly. You should always go via the property name, which will ensure that any getter/setter actions are honoured.

So if you code _property = 4, you have directly set the variable. If you code self.property = 4, you are effectively making the method call [self setProperty:4], which will go via the setter (which might do something such as enforce property having a max value of 3, or updating the UI to reflect the new value, for example).

Edit: I though it was worth mentioning that the setter (setProperty) will issue a _property = 4 internally to actually set the instance variable.

like image 29
Steve Ives Avatar answered Oct 07 '22 16:10

Steve Ives


when you are using the self.XX, you access the property via the setter or getter.

when you are using the _XX, you access the property directly skip the setter or getter.

like image 40
Joyal Clifford Avatar answered Oct 07 '22 17:10

Joyal Clifford