Alex Rivera | Logout

How can I create an empty array in objective C, and assign value into it one by one?

Asked 2010-02-25T15:26:07.493
19

In Java, I can do that :

int[] abc = new int[10];
for(int i=0; i<abc.length; i++){
   abc[i] = i;
}

How can I implement similar thing in Objective C?

I see some answer using NSMutableArray, wt's different between this and NSArray?

Edit
Report

1 Answer

11
NSMutableArray* abc = [NSMutableArray array];
for (int i = 0; i < 10; ++ i)
   [abc addObject:[NSNumber numberWithInt:i]];
return abc;

Here,

  • NSMutableArray is a "mutable" array type. There is also a constant array super-type NSArray. Unlike C++, ObjC's array is not typed. You can store any ObjC objects in an NSArray.
  • -addObject: appends an ObjC at the end of the array.
  • Since NSArrays can only store ObjC, you have to "box" the integer into an NSNumber first.

This is actually more similar to the C++ code

std::vector<int> abc;
for (int i = 0; i < 10; ++ i)
   abc.push_back(i);
return abc;
answered 2010-02-25T15:27:58.593

Your Answer