Question

In a chess game I would like to use a 2-dimensional array to track positions of pieces at the chess board.

Initially I thought to create an NSMuteableArray and indicate unoccupied squares by nil. The occupied slots should hold a pointer to a Piece object...

However the following code:

NSMutableArray* _board;
...

_board = [[NSMutableArray alloc] init];
for (int i = 0; i < 8; i++) {
    NSMutableArray *row = [[NSMutableArray alloc] init];
    for (int j = 0; j < 8; j++) {
        [row addObject:nil];
    }
    [_board addObject:row];
}

fails with the runtime error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

So nil can't be passed as argument to addObject... what to do here instead?

Was it helpful?

Solution

Try

NSMutableArray* _board;
...

_board = [[NSMutableArray alloc] init];
for (int i = 0; i < 8; i++) {
    NSMutableArray *row = [[NSMutableArray alloc] init];
    for (int j = 0; j < 8; j++) {
        [row addObject:[NSNull null]];
    }
    [_board addObject:row];
}

Reason for using [NSNull null] instead of nil can be seen here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top