在多维 NSMutableArray 中添加对象 [英] Adding objects in Multidimensional NSMutableArray
问题描述
我对如何在多维数组中添加对象感到很困惑.
I'm quite confused on how to add objects in multidimensional arrays.
初始化多维数组和简单数组一样吗?
Is initializing multidimensional arrays are the same with just a simple array?
这是我的初始化.
testList = [[NSMutableArray alloc] init];
我需要做类似的事情
testList[i][j] = item;
我试过了
[[[testList objectAtIndex:i]objectAtIndex:j] addObject:item];
但它似乎不起作用:(
推荐答案
你需要添加很多 C 来做到这一点.了解 NSMutableArray 的工作原理以及与 C/C++ 中已知的二维数组相比有何不同,这一点很重要.
You are add to much C to do this. This is important to know how to NSMutableArray works and how it's different compare to 2D arrays known from C/C++.
在可变数组中,您可以存储另一个数组.例如:
In mutable array you could store another arrays. For example:
NSMutableArray *first = [[NSMutableArray alloc] init];
NSMutableArray *second = [[NSMutableArray alloc] init];
[first addObject:second];
现在你在第一个数组的第一行有了数组!这很像 C/C++ 2D 数组.
Now you have array in first row in first array! This is something very like C/C++ 2D arrays.
因此,如果您想向 "0,0" 添加某个对象,请执行以下操作:
So if you want to add some object to "0,0" you do this:
NSString *mytest = [[NSString alloc] initWithString:@"test"];
[second addObject:mytest];
[first addObject:second];
所以现在你的 second 包含 NSStrings 而 first 包含 second.现在您可以随意循环播放.
So now your second contains NSStrings and first contains second. Now you can loop this like you want.
----如果你想要 1,0 你只需要 second NSMutableArray 的另一个实例.例如你有这个数组:
---- IF you want 1,0 you simply need another instance of second NSMutableArray. For example you have this array:
所以这里你将在 second 数组中有 3 个元素.
So here you will be have 3 elements in second array.
NSMutableArray *first = [[NSMutableArray alloc] init];
for(int i =0 ; i < your_size_condition ; i++) {//if you have size, if don't not a problem, you could use while!
NSArray *second = [[NSArray alloc] initWithObjects:"@something",@"somethingelse",@"more",nil];
[first addObject:second];
}
您可能想要实现 NSCopying 协议来做到这一点.
You may want to implement NSCopying protocol to do this.
这篇关于在多维 NSMutableArray 中添加对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!