2

I'm sorry I do not know Objective-C well.

Here is SomeClass.h :

@interface SomeClass : NSObject

@property NSString *property;

@end

We can use property in SomeClass.m as both

self.property

and

_property.

Which should I use?

Is there some situation to decide which way to use?

Thank you for your help.

Feel Physics
  • 2,773
  • 4
  • 22
  • 36

3 Answers3

7

Typically in standard practice, you only ever use _property in a getter/setter/init/dealloc method. In all other cases you use self.property or [self property]

Why?

Using _property is strictly used to assign or get a value directly, while using self.property is the same as calling [self property].

In this way, you can create custom getters/setters for the method that all classes are required to abide by when they use this variable, including the class holding the variable itself.

For example:

If I call object.property, I am essentially calling [object property]. Now this doesn't matter so much if you don't define custom methods, but if you have a custom getter or setter method in your object's class:

- (Type)property{
    return 2*_property;
}

//AND/OR

- (void)setProperty:(Type)property
{
    _property = 2*property;
}

Then there will be a difference between using _property and self.property.

Make sense?

Community
  • 1
  • 1
David
  • 21,070
  • 7
  • 57
  • 113
  • You should also use direct access in `init` and `dealloc`. See [here](http://qualitycoding.org/objective-c-init/), [here](https://github.com/NYTimes/objective-c-style-guide/issues/6) and [here](http://stackoverflow.com/a/1286227/1489997) – Sebastian Feb 13 '14 at 02:59
  • @Sebastian Answer updated. Thanks for pointing that out. – David Feb 13 '14 at 03:30
0

self.property calls the (generated) getter; equivalent to [self property].

_property accesses the variable directly.

The general recommendation is to use self.property, since the getter may be overridden to do something special, such as extra memory management, or lazy creation, or something else.

Krease
  • 14,501
  • 8
  • 47
  • 82
0

Use self.property. If you have specific reasons to ignore the setter of this property, use _property.

sCha
  • 1,291
  • 1
  • 10
  • 22