Complete and utter neophyte to Objective-C and the entire Mac platform so don’t flame me please =). Basically I’m trying to create a simple game. The game has a board which I’ve created a class for and a board is comprised of squares which I also created a class for (board and square respectively).
In my view controller I’m trying to instantiate a board and add boardSize^2 squares to said object. board contains an NSMutableArray *squares.
I’ve also created a convenience method which sets an NSNumber *boardSize called initWithDimension.
In my touchesBegan handler I have the following:
board *game_board = [[board alloc] initWithDimension:10];
int size = [game_board.boardSize intValue];
for(int i = 0; i <= size; i++) {
square *s = [[square alloc] init];
[game_board.squares addObject:s];
[s release];
}
NSLog(@"%i", size);
NSLog(@"%@", [game_board.squares objectAtIndex:0]);
…and I’m getting 10 (as expected) and then (null). This is probably glaringly obvious to an experienced developer, I’ve just struggled for an hour trying to solve it and have given up. I’ve tried it without the [s release] as well, same result. I’ve also imported square.h and board.h.
Any ideas what’s wrong here? Any other comments on what I’m brutalizing?
Thanks.
The core problem you’re facing is this: in the code you posted, you never assign an object reference to
game_board.squares, so it’s implicitly initialized tonil. When you calladdObject:onnil, nothing happens. This is defined behavior within the Objective-C language. So, you should add an assignment of the formsquares = [[NSMutableArray alloc] initWithCapacity:boardSize*boardSize]]before adding objects.You should be initializing your board within the
initWithDimensions:method. That’s the whole point of creating a class to begin with – encapsulating object behavior. Since theBoardis the manager of theSquareobjects, it should initialize and manage them.Stylistically, class names are preferably Pascal-cased, meaning that each word is upper-cased:
MyClassName. (In this case, preferBoardtoboardandSquaretosquare.)