stevenpcurtis stevenpcurtis - 5 months ago 33
Objective-C Question

2d NSArray with enumerated types in objective-c

I am creating a word search game with enumerated types for the cells. I need to create a 2 dimensional array, and to achieve this will code an NSArray of NSArrays holding objects of the enum type.

I looked at creating an array of enums, and did so. I am also capable of creating an NSArray of NSArrays. But creating an NSArray of NSArrays containing enumerated types dow not work how I'd expect it to:

My BoardCellState.h class:

typedef NS_ENUM(NSUInteger, BoardCellState) {
BoardCellStatePartOfWord = 0,
BoardCellStatePartOfWordSelected = 1,
BoardCellStateNotPartOfWord = 2,
BoardCellStateNotPartOfWordSelected = 3,};

My NSArray (10x10 grid)

NSArray *partofwordArray = [NSArray arrayWithObjects:[NSArray arrayWithObjects:@[@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStateNotPartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStateNotPartOfWord),@(BoardCellStateNotPartOfWord)], nil],
...(repeated 9 more times)...nil];

Now accessing partofwordArray does not function as I expect

int partofWordState = [partofwordArray [row][col] intValue];

results in unrecognised selector sent to call stack (intValue), where row and column are any integer between 0 and 9 (so within my grid)

My solution has been

id returnedID =partofwordArray[row][0];
int partofWordState = [returnedID[col] intValue];

Where once again any row and column are between 0 and 9.

Although this works it is hacky and I can't explain why. The line that creates an error makes much more sense, so why does it not work?


You are doing it are creating three dimension array here.. With your array defined as above you can get values like

int partofWordState = [partofwordArray [row][0][col] intValue];

It will work ..will not give any error.

for two dimension array you should define like following..

NSArray *partofwordArray = [NSArray arrayWithObjects:[NSArray arrayWithObjects:@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStateNotPartOfWord),@(BoardCellStatePartOfWord),@(BoardCellStateNotPartOfWord),@(BoardCellStateNotPartOfWord), nil] ,
....up to 9 ..

With this code you can actually access data the way you want.

int partofWordState = [partofwordArray [row][col] intValue];