簡體   English   中英

如何在Objective-C中添加和更新二維數組的對象?

[英]How to add and update the objects of two dimensional array in objective-c?

我想在Objective-C中創建一個二維數組,並將所有索引初始化為零。 每當我的數據(2D坐標)與任何行/列匹配時,我都希望通過值1升級相應的索引。 這樣一來,以后我就可以在任意點基於最大索引數掃描我的高度可能坐標。 例如:如果我的算法生成坐標(0,1),則第一行和第二列的索引必須增加一個。 非常感謝。

這是創建數組的方式。

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:[NSMutableArray arrayWithObjects:@"0",@"0",nil]];
[array addObject:[NSMutableArray arrayWithObjects:@"0",@"0",nil]];
NSLog(@"%@",array);

更新值

假設您要用值3更新index(0,1) ,您可以

[[array objectAtIndex:0] replaceObjectAtIndex:1 withObject:@"3"];
NSLog(@"%@",array);

用值4更新index(1,1)

[[array objectAtIndex:1] replaceObjectAtIndex:1 withObject:@"4"];
NSLog(@"%@",array);

希望能幫助到你。

干杯。

如果需要,可以使用數字並使用簡單的方法來編寫數組:

NSMutableArray * array2d = @[@[@0,@0], @[@0,@1]];

只是一個建議:

Objective-C是C的超集。因此,您也可以使用C數組的概念。

int array2D[5][5] = {0};//The compiler will automatically intialize all indces to 0.

或使用

memset(&a[0][0], 0, sizeof(int) * 5 * 5);

然后使用如下所示的簡單C賦值,

array2D[0][1] = 3;

更快,更簡單。

樣例代碼:

#include<stdio.h>
#include<string.h>

int main(int argc, char * argv[])
{
  int a[5][5];

  memset(&a[0][0], 0, sizeof(int) * 5 * 5);

  for(int  i = 0;  i < 5; i++)
  {
    for(int j = 0; j < 5; j++)
    {
      printf("%d ", a[i][j]);
    }

    printf("\n");
  }

  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM