I'm beginning Objective-C and I'm trying to create a multidimensionnal array of integers
, here is how I did it :
我开始了Objective-C我想创建一个多维的整数数组,我是这样做的:
File Constants.h (added in the Prefix.pch file)
文件常数。h(加上前缀。pch文件)
typedef enum {
BOARD_WIDTH=10,
BOARD_HEIGHT=20
} BoardSizeEnum;
File Board.m
文件Board.m
@implementation Board
{
NSInteger mBoard[BOARD_WIDTH][BOARD_HEIGHT];
}
I tried many many way of creating constants for my width
and height
and this way is the only one that seems (quite) correct... I also tried with define
but I don't like this because it's not typed (am I wrong for thinking that ?)...
我尝试了很多方法来为我的宽度和高度创建常量,这种方法是唯一看起来(非常)正确的方法。我也尝试过define,但我不喜欢这个,因为它没有类型(我这样想是错的吗?)
Is there a better way of creating this ? I feel it's not really clean...
有更好的方法来创造这个吗?我觉得不太干净……
Edit :
NSInteger*
to NSInteger
, I clearly want an array of integers
, not pointers.
编辑:NSInteger*到NSInteger,我显然想要一个整数数组,而不是指针。
2 个解决方案
#1
4
You shouldn't declare the sizes like that. Enums are usually used when you have multiple options and you want to give each option a name (instead of just using numbers).
你不应该这样申报尺寸。枚举通常用于当您有多个选项并且您想给每个选项一个名称(而不是仅仅使用数字)时。
To declare constants for your array, you have a few options.
要为您的数组声明常量,您有几个选项。
-
Use preprocessor macros:
使用预处理器宏:
#define BOARD_WIDTH 10
#定义BOARD_WIDTH 10
-
Use constants:
用常量:
static const int boardWidth = 10;
静态const int boardWidth = 10;
And your declaration is wrong. You're declaring a 2 dimensional array of NSInteger
pointers. It should be like this instead:
你的声明是错误的。声明一个二维NSInteger指针数组。应该是这样的:
// assuming width and height is declared as described above.
NSInteger mBoard[width][height];
#2
0
NSMutableArray *words[26];
for (i = 0;i<26;) {
words[i] = [[NSMutableArray alloc] init];
}
you can use it like this
你可以这样使用它
[words[6] addObject:myInt];
[words[6] insertObject:myInt atIndex:4];
[words[6] objectAtIndex:4];
//in this case 6 is the column number and 4 is the row.
#1
4
You shouldn't declare the sizes like that. Enums are usually used when you have multiple options and you want to give each option a name (instead of just using numbers).
你不应该这样申报尺寸。枚举通常用于当您有多个选项并且您想给每个选项一个名称(而不是仅仅使用数字)时。
To declare constants for your array, you have a few options.
要为您的数组声明常量,您有几个选项。
-
Use preprocessor macros:
使用预处理器宏:
#define BOARD_WIDTH 10
#定义BOARD_WIDTH 10
-
Use constants:
用常量:
static const int boardWidth = 10;
静态const int boardWidth = 10;
And your declaration is wrong. You're declaring a 2 dimensional array of NSInteger
pointers. It should be like this instead:
你的声明是错误的。声明一个二维NSInteger指针数组。应该是这样的:
// assuming width and height is declared as described above.
NSInteger mBoard[width][height];
#2
0
NSMutableArray *words[26];
for (i = 0;i<26;) {
words[i] = [[NSMutableArray alloc] init];
}
you can use it like this
你可以这样使用它
[words[6] addObject:myInt];
[words[6] insertObject:myInt atIndex:4];
[words[6] objectAtIndex:4];
//in this case 6 is the column number and 4 is the row.