NSMutable array vs C++ Object array



I just wanted clarification on something…in C++, when you initialize or declare an object array, it seems apparent in the initial
code what type of object you are creating:

For example:

int main()
  int userInput = 10;
//Here you are creating an array of Car objects
  Car *mycars = new Car[userInput];

In Objective-C, when you create a new array object, it looks like so

//  Portfolio.h
//  Stocks

#import <Foundation/Foundation.h>
#import "StockHolding.h"

@interface Portfolio : NSObject
    //Appears to only be saying I want an array of myStocks, but does not know what object type myStocks is
    NSMutableArray *myStocks;
//  Portfolio.m
//  Stocks

#import "Portfolio.h"

@implementation Portfolio
@synthesize myStocks;

-(void)addToPortfolio:(StockHolding *)a

        myStocks = [[NSMutableArray alloc] init];

    //Is this the point at which the compiler finally knows what kind of objects the array is going to hold?
    [myStocks addObject:a];

My question…in the header file, you are declaring a NSMutable array called myStocks…at that point, all the compiler knows is its an array that needs to be created, no object time appears to be specified until later in the Portfolio.m file, where you add an object to it [myStocks addObject:a] ?

I am coming from the C/C++ environment and it seems like from what I remember back then we had to be specific from the onset on all the array properties.



NSMutableArray is much more flexible and forgiving than a C/C++ array in two ways:

  1. You don’t have to give it a size. The NSMutableArray will grow and shrink as objects are added and removed.

  2. You don’t have to specify what sort of objects will be in the array. An NSMutableArray can hold instances of assorted types of objects. For example, you might have an NSMutableArray that held an NSDate, an NSString, and an NSDictionary.

I hope that helps.


NSMutableArray is a bit like:

std::vector <void*>;
// ma.mm

#import <vector>
#import <iterator>
#import <Foundation/Foundation.h>

int main (int, char *[])
   typedef std::vector <void*> MutableArray;

   MutableArray *array = new MutableArray;

   // Go wild
   array->push_back (array);
   array->push_back ((void*)main);
   array->push_back (@"Hello world!");

   for (MutableArray::const_iterator x = array->begin (); x != array->end (); ++x)
      NSLog (@"%p", *x);

   delete array;

   return 0;


Thank you guys…

I appreciate the quick feedback…

Its very “Fun” to play with the IDE and the the language. I did all my programming in undergraduate classes last few years and we were not allowed to use
the “cool” things, we learned off steam gauges( unix prompt , etc ) which I appreciate but its cool