0
@interface{
   NSArray *array;
}
@property (nonatomic, retain) NSArray *array;
@end

@implementation
@synthesize array;
   self.array = [[NSArray alloc] init];
   array = [[NSArray alloc] init];

[self.array objectAtIndex:2]; [array objectAtIndex:2];
@end

Is there a difference between them? Why should I use one over the other?

ssj
  • 881
  • 1
  • 10
  • 21
  • possible duplicate of [When to use self on class properties?](http://stackoverflow.com/questions/867001/when-to-use-self-on-class-properties) – Chuck Sep 18 '10 at 20:53

2 Answers2

4

self.array = foo is shorthand for [self setArray:foo] (i.e. you access the synthesized property methods), while just array = foo directly accesses the instance variable.

In exactly this case, you would create a memory leak with self.array = [[NSArray alloc] init]; since the property will retain it and the reference count would thus be 2 instead of 1. So better would be: self.array = [NSArray array];.

Which one to prefer is almost a matter of taste, but using the properties gives you a few advantages like automatic key-value coding support. It's also an advantage if you someday chose to do implement setArray: yourself so it can do additional stuff when the array is assigned (like reloading a UITableView). On the other hand, it's a little bit slower as it's an additional method call (only matters if called in a loop a lot). But for almost all applications it's better to be correct than as fast as possible. Using properties can make memory management easier for you.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
3

The property "array" is declared to retain on assignment (the retain in the brackets after @property signifies this). Because it has the same name as the "array" instance variable it uses that instance variable as it's backing store.

Effectively calling self.array = [[NSArray alloc] init]; is the same as calling array = [[[NSArray alloc] init] retain];

When you assign to the instance variable directly, not using the property, no action is taken on it, so array simply points to a new instance of NSArray without retaining it.

Jasarien
  • 58,279
  • 31
  • 157
  • 188
  • As a corollary to the above, the `self.array = [[NSArray alloc] init]` very likely (in fact, almost certainly) leaks; since you already own the object you're creating (the `NSArray`) and then your property is retaining it, causing you to own it twice. – jer Sep 18 '10 at 20:51
  • How about when accessing data, [self.array objectAtIndex:2] vs [array objectAtIndex:2] – ssj Sep 18 '10 at 20:58