对于 C,我会像这样初始化一个数组:
NSInteger x[3][10];行得通。
下面我有一个有效的单暗数组。想将所有这些移动到一个 2 dim 数组,我该如何初始化它?所以换句话说,采用下面的代码并使其适用于二维。
NSMutableArray *SRData;
SRData = [[NSMutableArray alloc] init];
NSMutableDictionary *SRRow;
SRRow = [[NSMutableDictionary alloc] init];
[SRRow setObject:@"Read" forKey:@"Descr"];
[SRRow setObject:@"Read2.png" forKey:@"Img"];
[SRRow setObject:@"Read the codes" forKey:@"Det"];
[SRData addObject:SRRow] ;
[SRRow release];
最佳答案
在 Objective-C 中,你只需要有一个数组数组就可以得到第二个维度。据我所知,没有速记法,因此您只能执行以下操作:
NSMutableArray *firstDimension = [[NSMutableArray alloc] init];
for (int i = 0; i < rows; i++)
{
NSMutableArray *secondDimension = [[NSMutableArray alloc] init];
[firstDimension addObject:secondDimension];
}
因此,您要做的就是将其他对象(在您的例子中是 NSMutableDictionary
)添加到 secondDimension
数组。用法如下:
[[firstDimension objectAtIndex:0] objectAtIndex:0];
编辑
完整代码示例:
NSMutableArray *SRData = [[NSMutableArray alloc] init]; //first dimension
NSMutableArray *SRRow = [[NSMutableArray alloc] init]; //second dimension
[SRData addObject:SRRow]; //add row to data
[SRRow release];
NSMutableDictionary *SRField = [[NSMutableDictionary alloc] init]; //an element of the second dimension
[SRField setObject:@"Read" forKey:@"Descr"];
//Set the rest of your objects
[SRRow addObject:SRField]; //Add field to second dimension
[SRField release];
现在,要到达该“字段”,您将使用如下代码:
[[SRData objectAtIndex:0] objectAtIndex:0]; //Get the first element in the first array (the second dimension)
关于iphone - 初始化 2 个昏暗数组 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8886276/