分配ivar

时间:2011-03-02 20:13:54

标签: iphone objective-c memory-management

为什么我不能简单:

self.list = [[NSArray alloc] initWithObjects: @"Who Hash", @"Bubba Gump Shrimp Étouffée", @"Who Pudding", @"Scooby Snacks", @"Everlasting Gobstopper", @"Green Eggs and Ham", @"Soylent Green", @"Hard Tack", @"Lembas Bread", @"Roast Beast", @"Blancmange", nil];

而不是:

NSArray *array = [[NSArray alloc] initWithObjects:@"Who Hash", @"Bubba Gump Shrimp Étouffée", @"Who Pudding", @"Scooby Snacks", @"Everlasting Gobstopper", @"Green Eggs and Ham", @"Soylent Green", @"Hard Tack", @"Lembas Bread", @"Roast Beast", @"Blancmange", nil];
self.list = array;

2 个答案:

答案 0 :(得分:4)

其实你可以。但是如果list属性被声明为retain,你必须这样做:

self.list = [[[NSArray alloc] initWithObjects: @"Who Hash", @"Bubba Gump Shrimp Étouffée", @"Who Pudding", @"Scooby Snacks", @"Everlasting Gobstopper", @"Green Eggs and Ham", @"Soylent Green", @"Hard Tack", @"Lembas Bread", @"Roast Beast", @"Blancmange", nil] autorelease];

或更短:

self.list =  [NSArray arrayWithObjects: "Who Hash", @"Bubba Gump Shrimp Étouffée", @"Who Pudding", @"Scooby Snacks", @"Everlasting Gobstopper", @"Green Eggs and Ham", @"Soylent Green", @"Hard Tack", @"Lembas Bread", @"Roast Beast", @"Blancmange", nil];

否则你会得到泄密。

答案 1 :(得分:2)

您发布的两种方法都在泄露。

假设list被声明为这样的属性......

@property (nonatomic, retain) NSArray *list;

然后我们知道,当通过合成的setter设置列表时,使用self.list = xxx,它将被保留并保留计数为1.此外,通过调用alloc / init,retain会再次突然变为2。话虽如此,我们可以用内存安全的方式重写你的两种方法,比如......

self.list = [[[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil] autorelease];

self.list = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];

NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", nil];
self.list = array;
[array release];