user637530
user637530

Reputation:

allocating ivar

why I can't simple:

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];

instead of:

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;

Upvotes: 1

Views: 139

Answers (2)

Mark Adams
Mark Adams

Reputation: 30846

Both methods you have posted are leaking.

Assuming that list is declared as a property like this...

@property (nonatomic, retain) NSArray *list;

Then we know that when setting list via the synthesized setter, using self.list = xxx, that it will be retained and have a retain count of 1. Additionally by calling alloc/init, the retain bumps up again to 2. Having said that, we could rewrite your two approaches in a memory safe way, like this...

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

or

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

or

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

Upvotes: 2

Max
Max

Reputation: 16719

Actually you can. But if list property is declared as retain you have to do it like this:

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];

OR even shorter:

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];

Otherwise you'll get the leak.

Upvotes: 4

Related Questions