Memory Management - [NSArray array] vs [[NSArray init] alloc]

Discussion in 'Mac Programming' started by Spike099, Mar 25, 2008.

  1. Spike099 macrumors regular

    Feb 18, 2007
    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?
  2. phjo macrumors regular

    Jan 8, 2008
    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.

  3. HiRez macrumors 603


    Jan 6, 2004
    Western US
    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.
  4. Monkaaay macrumors 6502


    Jun 19, 2006
    Richmond, VA
    Glad someone asked this question. I was kind of wondering the same. :apple:
  5. kainjow Moderator emeritus


    Jun 15, 2000
    From the documentation:

    So it's not meant to be used with NSArray.
  6. Spike099 thread starter macrumors regular

    Feb 18, 2007
    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.

Share This Page