iPhone: How to access NSMutableArray two dimensional setting?
I am using insertObject for NSMutableArray for storing values into two dimensional array like below for example.
开发者_StackOverflow中文版[mutableArrayPtr insertObject:[NSMutableArray arrayWithObjects:firstData, secondData,nil] atIndex:index];
I think, it is correct way of storing values in two dimensional array in Obj C.
I want to access it at later point of time. How can i do that?
Thanks!
The way you are doing it is perfectly fine. NSArray
's don't have native two dimensional syntax like primitive arrays (int[][]
, double[][]
, etc.) in C do. So instead, you must nest them using an array of arrays. Here's an example of how to do that:
NSString *hello = @"Hello World";
NSMutableArray *insideArray = [[NSMutableArray alloc] initWithObjects:hello,nil];
NSMutableArray *outsideArray = [[NSMutableArray alloc] init];
[outsideArray addObject:insideArray];
// Then access it by:
NSString *retrieveString = [[outsideArray objectAtIndex:0] objectAtIndex:0];
To access your array at a later point in time, you would do something like:
NSArray* innerArray = [mutableArrayPtr objectAtIndex:0];
NSObject* someObject = [innerArray objectAtIndex:0];
Of course, change 0
to whatever index you actually need to retrieve.
EDIT:
Q: Is it "initWithObjects" (or) "insertObject:[NSMutableArray arrayWithObjects:imagePtrData,urlInStr,nil]" for two dimension?
A: initWithObjects
and insertObject
would both allow you to create two dimensional arrays. For example you could do:
NSMutableArray* arrayOne = [[NSMutableArray alloc] initWithObjects:[NSArray initWithObjects:@"One", @"Two", @"Three", nil], [NSArray initWithObjects:[@"Four", @"Five", @"Six", nil], nil];
// NOTE: You need to release the above array somewhere in your code to prevent a memory leak.
or:
NSMutableArray* arrayTwo = [NSMutableArray array];
[arrayTwo insertObject:[NSArray arrayWithObjects:@"One", @"Two", @"Three", nil] atIndex:0];
精彩评论