views:

60

answers:

2

Hi, everyone,

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.

+1  A: 

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];
Jacob Relkin
Thank you for your reply. Is it possible to create a dynamic array and not set the length in the begin?
Questions
@MarkSiu, Yes. If you want, I can give you an example of this.
Jacob Relkin
Thank you for your reply. Would you mind to give me the example. Thank you very much.
Questions
I edited my answer already.
Jacob Relkin
Thank you very much. and I would like to ask a question. why it needs the [inner release]; in that position.
Questions
@MarkSiu, because we used `alloc`, `copy`, or `init` in our instantiation statement, which subsequently bumps the retain count to `1` on instantiation.
Jacob Relkin
A: 

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];
badweasel
Does not answer the question (OP is asking about a 2-dimensional array), and is incorrect to boot (indexes start at 0, so the index of the last object is i-1, not i).
David Gelhar
I did not notice the 2D thing... and yes my i was incorrect for the last object. Thanks for pointing it out. I changed my answer to the way I would do a 2D array.
badweasel