views:

98

answers:

3

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?

A: 

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.

cmsjr
and the disadvantage to removing "self" and using: "hintArray = [[NSArray alloc] initWithObjects:@"Year", "@Capital", ..., nil];" would be that you're also bypassing any custom setter/getter code, right? But if you know there's no setter/getter code is this ok? or also considered bad Cocoa form?
Meltemi
lol, I'm just getting a handle on Objective-C memory management myself, so I wouldn't presume to say what is and isn't bad form. eJames and fbrerton seem to have a much better handle on the topic.
cmsjr
+4  A: 

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
fbrereto
ack!, please don't do this! Your code is assuming that the -hintArray method will return exactly the same object you passed into the -setHintArray: setter method. If it doesn't (and this is quite easily possible) your app will crash at some point.
Mike Abdullah
+7  A: 

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).

e.James
That is great! Using auto-released code is the way to go for me.
Bryan