3
votes

I want to ask about the objective C question. I want to create a 2D NSArray or NSMutableArray in objective C. What should I do? The object stored in the array is NSString *. Thank you very mcuh.

3

3 Answers

6
votes

This is certainly possible, but i think it's worthy to note that NSArrays can only hold objects, not primitive types.

The way to get around this is to use the primitive wrapper type NSNumber.

NSMutableArray *outer = [[NSMutableArray alloc] init];

NSMutableArray *inner = [[NSMutableArray alloc] init];
[inner addObject:[NSNumber numberWithInt:someInt]];
[outer addObject:inner];
[inner release];

//do something with outer here...
//clean up
[outer release];
1
votes

Try NSMutableDictionary with NSNumbers as keys and arrays as objects. One dimension will be the keys, the other one will be the objects.

To create the specific "2D array"

NSMutableDictionary *twoDArray = [NSMutableDictionary dictionary];
for (int i = 0; i < 10; i++){
    [twoDArray setObject:arrayOfStrings forKey:[NSNumber numberWithInt:i]];
}

To pull the data

NSString *string = [[twoDArray objectForKey:[NSNumber numberWithInt:3]] objectAtIndex:5];
//will pull string from row 3 column 5 -> as an example
-1
votes

Edited to make my answer more applicable to the question. Initially I didn't notice that you were looking for a 2D array. If you know how many by how many you need up front you can interleave the data and have a stride. I know that there are probably other (more objective standard) ways of having arrays inside of an array but to me that gets confusing. An array inside of an array is not a 2 dimensional array. It's just a second dimension in ONE of the objects. You'd have to add an array to each object, and that's not what I think of as a 2 dimensional array. Right or wrong I usually do things in a way that makes sense to me.

So lets say you need a 6x6 array:

int arrayStride=6;
int arrayDepth=6;
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:arrayStride*arrayDepth];

I prefer to initialize the array by filling it up with objects;

for(int i=0; i<arrayStride*arrayDepth; i++) [newArray addObject @"whatever"];

Then after that you can access objects by firstDim + secondDim*6

int firstDim = 4;
int secondDim = 2;
NSString *nextString = [newArray objectAtIndex:firstDim+secondDim*6];