View Full Version : Memory Management - [NSArray array] vs [[NSArray init] alloc]
Mar 26, 2008, 12:03 AM
Basically my question is should I ever use [NSArray array]? From my understanding, you do not have to release the memory. But how does the array know when you are finished with it? Should I be autoreleasing arrays initialized in this fashion?
Mar 26, 2008, 01:06 AM
Short answer : never...
It would not make much sense (to create an empty immutable array...), but [NSMutableArray array] would...
Now, to answer your question, [NSMutableArray array] would give an autoreleased object, so you don't want to autorelease it again...
But you could add a few objects and return it in a method, and the caller would then be responsible for retaining it.
Mar 26, 2008, 01:17 AM
This is a convenience constructor. They are already autoreleased, so you don't need to do that (in fact, don't do this). You never need to use them but they can be...well...convenient. It's equivalent to writing NSArray *myArray = [[[NSArray alloc] init] autorelease];
It'll get released when the current autorelease pool does, which could be at some later time. If you want the object to persist beyond the current scope you must assign it to an instance holder variable and send it a retain message.
Mar 26, 2008, 07:23 PM
Glad someone asked this question. I was kind of wondering the same. :apple:
Mar 26, 2008, 08:01 PM
From the documentation:
This method is used by mutable subclasses of NSArray.
So it's not meant to be used with NSArray.
Mar 27, 2008, 07:52 AM
Thanks for the replies. I was actually using a mutable array in my project, but used an immutable for the example. Looks like I won't be using it, I'm trying to stay away from autoreleasing.