Search code examples
objective-cnsmutablearraynsrangeexception

NSRangeException index 1 beyond bounds [0 .. 0] for non-empty array


Context: I'm currently on Assignment 2 for Stanford's most recent cs193p course on iTunes U. I'm trying to avoid simply looking up the solutions, but I'm stuck.

Problem: For the following code:

for (Card *c in self.chosenCards) { // for debugging purposes
    NSLog(@"Card: %@ index: %d", c.contents, [self.chosenCards indexOfObject:c]);
}

[self.chosenCards removeObjectAtIndex:0];

I keep getting the following result:

2014-11-30 14:58:11.487 Matchismo[12262:60b] Card: 5clubs♦️ index: 0
2014-11-30 14:58:11.487 Matchismo[12262:60b] Card: 6clubs♣️ index: 1
2014-11-30 14:58:23.714 Matchismo[12262:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

Why ): ? Obviously my array contains an object at index 0, and evidently the bounds of the array extend past [0 .. 0].


Solution

  • Most likely the problem is somewhere else (the index reported in the error is 1 after all). Try to put an exception breakpoint in order to identify the line that is causing the exception ( and possibly save you a lot of time and confusion on any similar issues in the future :) )