如何在 Objective C 中构建多维对象数组 [英] How to Build a MultiDimensional Array of Objects in Objective C
问题描述
可能的重复:
如何创建多维数组?
我是编程和目标 C 的新手,所以虽然我在这里发现了一些讨论多维数组的问题,但我不太明白我需要做什么来构建和使用我自己的数组.
I'm new to programming and objective C, so although I have found a few questions on here that discuss multidimensional arrays, I'm not quite getting what I need to do in order to build and use my own.
我需要制作一个有 16 行 3 列的数组.该数组需要接受字符串对象.我不知道如何创建、填充或访问其内容.有没有好心人帮我分解一下?
I need to make an array that has 16 rows and 3 columns. The array needs to accept string objects. I do not know how to create this, fill it, or access its contents. Would anyone be kind enough to break it down for me?
推荐答案
我建议您使用 C 数组,因为 NSArray
不支持多维.你可以像这样声明你描述的数组:
I'd suggest you use a C-array, as an NSArray
doesn't support multiple dimensions. You could declare the array you described like this:
NSString *stringArray[16][3];
设置和访问该数组的任何字符串非常简单:
Setting and accessing any string of this array is quite straight-forward:
stringArray[7][1] = @"Stringstringstring";
NSString *string = stringArray[3][0];
但是,您可以使用 NSArray
(或 NSMutableArray
),但这会不太优雅:
However, you could use an NSArray
(or NSMutableArray
), but that would be a bit less elegant:
NSArray *stringArray = [NSArray arrayWithObjects:
[NSMutableArray array],
[NSMutableArray array],
[NSMutableArray array], nil];
这三个 NSMutableArray
将是二维数组的三列.
Those three NSMutableArray
s would be the three columns of your two-dimensional array.
编辑
使用 NSArray
,使用循环来填充它可能更容易:
Using an NSArray
, it might be easier to use a loop to fill it:
NSMutableArray *stringArray = [NSMutableArray array];
for (int column = 0; column < 3; column++)
{
NSMutableArray *columnArray = [NSMutableArray array];
for (int row = 0; row < 16; row++)
[columnArray addObject:[NSString stringWithFormat:@"Row %i, column %i", row, column]];
[stringArray addObject:columnArray];
}
这篇关于如何在 Objective C 中构建多维对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!