NSMutableArray not being filled before it needs to be loaded

97 views Asked by At

I'm attempting to set up a simple Mac-based 2D tiling engine, using a 2D NSMutableArray for mapping purposes. I am using a subclass of NSViewController with a reference to the map object (which contains said array) and passing drawing requests for tile data through it to the map in the interests of maintaining MVC integrity. However, my application seems to not be populating the array with objects before my drawRect code begins firing.

Every time I run this app as written, my window fails to load and I receive the error message "-[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array" in the debugger. As far as I can tell, my array should be completely initialized with zeroes before the view is actually displayed or needs to be drawn.

Here is the -loadView method from my NSViewController subclass:

- (void)loadView
{
    currentMap = [[TestMap alloc] init];
    [super loadView];
}

and here is the init method from my map object:

- (id)init
{
    dimensions = NSMakeSize(15.0,20.0);
    tileset = [[TestTileset alloc] init];
    map = [NSMutableArray arrayWithCapacity:15];
    for (int i = 0; i == 14; i++)
    {
        NSMutableArray *tempRow = [NSMutableArray arrayWithCapacity:20];
        for (int j = 0; j == 19; i++)
        {
            NSNumber *tempID = [NSNumber numberWithInt:0];
            [tempRow addObject:tempID];
        }
        [map addObject:tempRow];
    }
    return self;
}

Judicious use of breakpoints has indicated that

[super loadView]

is somehow being called before init begins its for loops - and obviously, my drawRect code which has to reference the array follows on from there and fails quickly. I must be doing something wrong or out of order, but I cannot figure out what it might be.

1

There are 1 answers

1
Sergey Kalinichenko On BEST ANSWER

You have == instead of !=, so neither of your for loops executes. I think the loops should be as follows:

for (int i = 0; i != 15; i++)
{
    NSMutableArray *tempRow = [NSMutableArray arrayWithCapacity:20];
    for (int j = 0; j != 20; j++)
    {
        NSNumber *tempID = [NSNumber numberWithInt:0];
        [tempRow addObject:tempID];
    }
    [map addObject:tempRow];
}