2011-04-18 34 views
0

我正在使用insertObject for NSMutableArray将值存储到二维数组中,例如下面的例子。iPhone:如何访问NSMutableArray二维设置?

[mutableArrayPtr insertObject:[NSMutableArray arrayWithObjects:firstData, secondData,nil] atIndex:index]; 

我认为,这是在的OBJ C.

存储在二维数组值的正确方法我想在以后的时间点来访问它。我怎样才能做到这一点?

谢谢!

回答

1

你这样做的方式非常好。NSArray在C中没有本地二维语法,如原始数组(int[][],double[][]等)。相反,您必须使用数组数组来嵌套它们。下面是如何做到这一点的例子:

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]; 

要在以后的某个时间访问阵列,你会做这样的事情:

NSArray* innerArray = [mutableArrayPtr objectAtIndex:0]; 
NSObject* someObject = [innerArray objectAtIndex:0]; 

当然,改变0到任何指标,你居然需要检索。


EDIT

问:它是 “initWithObjects”(或) “insertObject:[NSMutableArray里arrayWithObjects:imagePtrData,urlInStr,零]” 为二维?

答:initWithObjectsinsertObject既能允许您创建二维数组。例如,你可以这样做:

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. 

或:

NSMutableArray* arrayTwo = [NSMutableArray array]; 
[arrayTwo insertObject:[NSArray arrayWithObjects:@"One", @"Two", @"Three", nil] atIndex:0]; 
+0

它是 “initWithObjects”(或) “insertObject:[NSMutableArray的arrayWithObjects:imagePtrData,urlInStr,零]” 两个维度? – Getsy 2011-04-18 12:55:46

+0

由于CFArray具有本机2D语法?内置的C数组类型“T [n]”与CFArray不同。 – kennytm 2011-04-18 12:59:19

+0

@KennyTM:谢谢你的提示,我看你是对的!我已经更新了答案以反映这个珍闻。再次感谢,我每天都会学到新的东西。 – FreeAsInBeer 2011-04-18 13:02:23