how to create a NSarray without intial value?

Discussion in 'Mac Programming' started by saleh.hi.62, Nov 1, 2011.

  1. saleh.hi.62 macrumors member

    Jul 25, 2011
    how to create a NSarray without initial value? i want to create an array and fill that during the running program.
  2. robbieduncan Moderator emeritus


    Jul 24, 2002

    NSArray *myArray=[[NSArray alloc] init];
    Edit to add: of course NSArray instances are immutable. If you want to add/remove objects use NSMutableArray instead of NSArray
  3. Partron22 macrumors 68020


    Apr 13, 2011
    If 'Attempt to mutate immutable object' is a problem, you might instead use
    + arrayWithCapacity:
    – initWithCapacity:
    from the NSMutableArray Class
  4. Sydde macrumors 68020


    Aug 17, 2009
    Most mutable subclasses of immutable objects return mutable objects with the superclass method, where applicable. For instance, [NSMutableArray arrayWithArray:someArray] will return a mutable array. If a method creates an autoreleased object (class methods), it will match the class used to create it (at least in terms of mutability). If a method typically returns a different object (instance methods), it will almost always match the mutability of the (super)class that implements the method.

    The linguistic rule of thumb is: if the method contains the word "With", called class mutability will be preserved; if the method contains the word "By", it will returned object will correspond to the class that implements the method (usually the immutable superclass).
  5. saleh.hi.62 thread starter macrumors member

    Jul 25, 2011
    actually what i exactly want is an array without initial value, and want to add infinite item during the running program, if i set the capacity at first that'll be possible to add extra item more than capacity later on?
  6. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    You want an NSMutableArray. If you start with a capacity then exceed it, it will grow. You don't have to start with an initial capacity, but resizing is expensive.

  7. gnasher729 macrumors P6


    Nov 25, 2005
    Excuse me, but what does the documentation in XCode say?

    It is all easy to ask questions here, but do you think you should base your programming career on the help of strangers? I would suggest that you demonstrate your willingness to learn by looking up the documentation of arrayWithCapacity and posting it here, just to demonstrate to everyone here that you are not just too lazy to learn.

    If you don't know how to look it up, ask about it here, because knowing how to look up documentation is hundred times more important than knowing the details of one method.

Share This Page