Bryan
Bryan

Reputation: 17601

Understanding Cocoa Memory

What is the advantage of doing this:

NSArray *array = [[NSArray alloc] initWithObjects:@"Year", "@Capital", ..., nil];
self.hintArray = array;
[array release];

Instead of assigning directly to my class variable like this:

self.hintArray = [[NSArray alloc] initWithObjects:@"Year", "@Capital", ..., nil];

Why do we create a temporary local object then release it instead of just assigning to our class variable?

Upvotes: 3

Views: 135

Answers (3)

James Eichele
James Eichele

Reputation: 119194

Others have already pointed out the memory issues, but here is the best way to do it in a single step:

self.hintArray = [NSArray arrayWithObjects:@"Year", "@Capital", ..., nil];

The convenience class method +arrayWithObjects returns an array that has already been autoreleased, so you simply don't need to worry about it any more. Your property accessor will take care of copying or retaining it. (assuming, of course, that your hintArray property is set up as a retain or copy property).

Upvotes: 7

fbrereto
fbrereto

Reputation: 35945

You could, but you have to remember to release it once before moving on. The assignment to self.hintArray (assuming it is a synthesized setter that retains on set) will bump the retainCount:

NSArray *array = [[NSArray alloc] initWithObjects:...]; // retainCount is 1
self.hintArray = array; // retainCount is 2
[array release]; // retainCount is 1

and:

self.hintArray = [[NSArray alloc] initWithObjects:...]; // retainCount is 2:
                                                        // one for the alloc
                                                        // and one for the assign
[self.hintArray release]; // retainCount is 1

Upvotes: 4

cmsjr
cmsjr

Reputation: 59225

Because in the Objective-C reference counted memory management scheme the creation of the array will increment the reference count and if you do not store the return value in a variable you can send a release message to you will have no way to decrement that count and will introduce a memory leak.

Upvotes: 0

Related Questions