对于C,我会初始化一个这样的数组:
NSInteger x [3] [10];这很有效。
下面我有一个可用的暗淡阵列。想将所有这些移动到2个暗淡的阵列,我该如何初始化它?换句话说,请使用下面的代码并使其适用于2维。
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];
答案 0 :(得分:3)
在Objective-C中,您只需拥有一组数组即可获得第二个维度。据我所知,没有简写,所以你不得不做如下的事情:
NSMutableArray *firstDimension = [[NSMutableArray alloc] init];
for (int i = 0; i < rows; i++)
{
NSMutableArray *secondDimension = [[NSMutableArray alloc] init];
[firstDimension addObject:secondDimension];
}
所以你要做的就是将你的其他对象(在你的情况下,NSMutableDictionary
s)添加到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)