Stupid Bug

The other day as I was tracking down a bug, I almost kicked myself when I saw the problem. The code was something like:

int i = 0;
int count = [array count];
for (i = 0; i < count; i++)
{
	if ([[array objectAtIndex:i] intValue] == 3)
	{
		[array removeObjectAtIndex:i];
	}
}

The problem with this code, if you’re a Cocoa programmer, should be obvious. If any of the elements are equal to 3, then when you get to the last or near the last element, there are no objects left in the array and it blows up. The proper way to do this, of course is:

int i = 0;
int count = [array count];
for (i = count - 1; i >= 0; i++)
{
	if ([[array objectAtIndex:i] intValue] == 3)
	{
		[array removeObjectAtIndex:i];
	}
}

By counting down instead of counting up, the problem is solved. What annoys me about this code I wrote is that I’ve done something similar many times. You’d think I’d learn by now.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.