开发者

Why or why not call an object with a "self." prefix?

@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 b开发者_运维问答etween them? Why should I use one over the other?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜