Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a 2D NSArray or NSMutableArray in objective C?

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.

like image 548
Questions Avatar asked Sep 12 '26 12:09

Questions


2 Answers

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];
like image 54
Jacob Relkin Avatar answered Sep 14 '26 08:09

Jacob Relkin


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
like image 31
Martin Herman Avatar answered Sep 14 '26 08:09

Martin Herman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!