@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?
self.array = foois shorthand for[self setArray:foo](i.e. you access the synthesized property methods), while justarray = foodirectly 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.