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

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

  1. macrumors regular

    Joined:
    Feb 18, 2007
    Location:
    Canada
    #1
    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. macrumors regular

    Joined:
    Jan 8, 2008
    #2
    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.

    phjo
     
  3. macrumors 601

    HiRez

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #3
    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. macrumors 6502

    Monkaaay

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

    kainjow

    Joined:
    Jun 15, 2000
    #5
    From the documentation:

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

    Joined:
    Feb 18, 2007
    Location:
    Canada
    #6
    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