Andy M
Andy M

Reputation: 6065

Declare constant for 2 dimensional array's size

I'm beginning Objective-C and I'm trying to create a multidimensionnal array of integers, here is how I did it :

File Constants.h (added in the Prefix.pch file)

typedef enum {
    BOARD_WIDTH=10,
    BOARD_HEIGHT=20
} BoardSizeEnum;

File 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 ?)...

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.

Upvotes: 2

Views: 526

Answers (2)

DrummerB
DrummerB

Reputation: 40211

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.

  1. Use preprocessor macros:

    #define BOARD_WIDTH 10

  2. Use constants:

    static 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:

// assuming width and height is declared as described above.
NSInteger mBoard[width][height]; 

Upvotes: 4

Rich Fox
Rich Fox

Reputation: 2194

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.

Upvotes: 0

Related Questions