0

Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
Difference between self.ivar and ivar?
Synthesized property and variable with underscore prefix: what does this mean?

To use property in object c, I have two choices, which one should i use?

choice1: self.property = xxxx;

choice2: _property = xxx

For example:

//.h file

@interface ViewController : UIViewController

    @property (retain, nonatomic) NSArray *myArray;

@end

//.m file

@interfaceViewController ()

@end

@implementation ViewController

- (void)doing {

    _myArray = [[NSArray alloc] init]; //choice one
    self.myArray = [[NSArray alloc] init]; //choice two
}
@end
Community
  • 1
  • 1
LiangWang
  • 8,038
  • 8
  • 41
  • 54

2 Answers2

2

You are doing two completely different things.

_myVar = [[NSArray alloc] init];

In the above code you're accessing directly the variable.

self.myVar = [[NSArray alloc] init];

In the above code you're calling the setter method, which is equivalent to

[self setMyVar:[[NSArray alloc] init]];

Usually the setter (along with getter) provides memory management and synchronization features therefore is preferable and generally more safe to use it, instead of accessing the ivar directly.

The underscore syntax is merely a convention not to confuse the ivar and the property, since a typical mistake is to get mistaken with that and accidentally use myVar instead of self.myVar. Using the underscore syntax is an attempt to discourage that bad practice.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
0

I know this question is quit frequent but I will answer it anyway.

The underscore syntax accesses the instance variable that backs the property while the dot syntax is just a wrapper for the accessory method:

object.property == [object property]
object.property = x == [object setProperty:x]

So you should use the dot syntax or the accessory method whenever possible to ensure that everything is taken care of. For example the Garbage Collection in non ARC apps. You have to use the instance variable for things like initializing, deallocating or a custom accessory method but these are special cases. To get a detailed overview read the chapter about properties in the Objective-C manual: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW1

SIGKILL
  • 390
  • 1
  • 9