【问题标题】:How to create 2D array and the size is given as a variable in objective-c如何创建二维数组,大小在objective-c中作为变量给出
【发布时间】:2015-11-14 11:24:43
【问题描述】:

我是 Objective-c 的新手。我在二维数组中遇到了麻烦。因为我有一些javascript知识。我会尝试用javascript解释它。

var row = 10;
var col = 10;
var array[row][col];

for (var i = 0; i < row; i++){
    for (var j = 0; j < col; j++){
        //do something in here
    }
}

row = 20;
col = 20;

for (var i = 0; i < row; i++){
    for (var j = 0; j < col; j++){
        //do something in here
    }
}

如何在 Objective-c 中编写代码?

【问题讨论】:

  • 在 ECMAScript 中,var array[row][col] 是一个语法错误。
  • 在目标 c 中,您在声明变量时不指定数组的大小。您只需分配一个 NSMutableArray 并将 NSMutableArrays 添加到其中。
  • 我想我和java混在一起了...

标签: javascript ios objective-c xcode


【解决方案1】:

希望这会有所帮助:

NSInteger row = 10;
NSInteger col = 10;

// Array with variable size. For fixed size, use [[NSMutableArray alloc] initWithCapacity:row]
NSMutableArray* array = [NSMutableArray new];

for (NSInteger i = 0; i < row; i++) {

    // You must add values before you can access them. You cannot access a value at an index which is greater than the size of the array

    NSMutableArray* colArray = [NSMutableArray new];
    [array addObject:colArray];

    for (NSInteger j = 0; j < col; j++) {


        [colArray addObject:someObject];

        // You can access the array like such:
        id object = array[i][j];

        // You can change an existing value in the array using the same notation:
        array[i][j] = someObject;

        // You cannot set an array value to nil or null. Instead use NSNull which is an object you can use to represent a null value:
        array[i][j] = [NSNull null];
    }
}


// You can also initialise an array with the following notation if you know the values in advance:

NSArray* anotherArray = @[objectOne, objectTwo, objectThree];

// Similarly, you can create a 2-dimensional array as follows:

NSArray* twoDimensionalArray = @[
                                 @[rowOneColumnOne, rowOneColumnTwo, rowOneColumnThree],
                                 @[rowTwoColumnOne, rowTwoColumnTwo, rowTwoColumnThree]
                                 ];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 2012-03-12
    相关资源
    最近更新 更多