ecbtln
ecbtln

Reputation: 2746

objective c array of booleans

I am working on a game that will have a two dimensional board of dots, each with one boolean attribute (occupied/not occupied). I was thinking the best way to accomplish this is to create a simple c array of Booleans. This will be much more efficient than creating a mutablearray. I'm just confused the best way to accomplish this. The trouble is that I don't know the size of the board until I initialize the board object. The interface looks like this:

@interface TouchBoard : NSObject{
NSInteger height,width;
BOOL dots[10][10];

}

And the implementation like this:

-(id)initWithHeight:(NSInteger)rows Width:(NSInteger)columns{
    if ( self = [super init]){
        height = rows;
        width = columns;
        dots[height][width];
    }
    return self;

}

Trouble is, in the interface, if i try to declare the dots variable with a dynamic number of indices, dots[][], it'll just give me an error. Obviously I don't know the size of the array until the object is initialized, but after that it's not going to be changing and only its elements will be changing from true/false.

What is the best way to accomplish this?

Upvotes: 0

Views: 2811

Answers (1)

Macmade
Macmade

Reputation: 53950

In your interface, declares:

BOOL ** dots;

Then, you'll need to use malloc, to dynamically allocate memory:

int i;

dots = malloc( rows * sizeof( BOOL * ) );

for( i = 0; i < rows; i++ )
{
    dots[ i ] = calloc( columns, sizeof( BOOL ) );
}

Don't forget to free in your dealloc method:

int i;

for( i = 0; i < rows; i++ )
{
    free( dots[ i ] );
}

free( dots );

Upvotes: 6

Related Questions