为什么我不能简单:
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;
答案 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];