访问2D数组并将字符串传递给label.text

时间:2010-04-29 05:47:24

标签: objective-c arrays 2d

我正在尝试创建2D数组并使用NSStrings对其进行初始化。 当我尝试将数组的内容从数组复制到label.text时,应用程序崩溃。

NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];

[array addObject:[NSMutableArray arrayWithObjects:
                   [NSArray arrayWithObjects: @"0-0", @"0-1", @"0-2", nil],
                   [NSArray arrayWithObjects: @"1-0", @"1-1", @"1-2", nil],
                   [NSArray arrayWithObjects: @"2-0", @"2-1", @"2-2", nil],
                   nil]];

label.text = [[array objectAtIndex:0] objectAtIndex:0];

知道为什么以及我做错了什么?

1 个答案:

答案 0 :(得分:2)

您正在创建一个3D数组(数组数组),而不是2D数组(数组数组)。使用此:

[array addObject:[NSArray arrayWithObjects: @"0-0", @"0-1", @"0-2", nil]];
[array addObject:[NSArray arrayWithObjects: @"1-0", @"1-1", @"1-2", nil]];
[array addObject:[NSArray arrayWithObjects: @"2-0", @"2-1", @"2-2", nil]];

或者这个:

NSMutableArray* array = [NSMutableArray arrayWithObjects:
                         [NSArray arrayWithObjects: @"0-0", @"0-1", @"0-2", nil],
                         [NSArray arrayWithObjects: @"1-0", @"1-1", @"1-2", nil],
                         [NSArray arrayWithObjects: @"2-0", @"2-1", @"2-2", nil],
                         nil]];