Constant bugs from [NSArray count] being unsigned

I'm creating bugs over and over by failing to notice the consequences of [NSArray count] being unsigned. Today's example is relatively unusual:

for (int i = -1; i < [myArray count]; i++) {

This loop never executes! You need (int)[myArray count]. My usual mistake is:

for (int i = 0; i < [myArray count] - 1; i++) {

If the array is empty, this loop executes basically forever because [myArray count]-1 overflows the unsigned int.

I do use fast enumeration where possible, but in this project I very often need to refer the objects at indexes i-1 and i+1 while processing object i and it doesn't seem to lend itself to that. Any other tips for avoiding these bugs, other than just being less incompetent?


Firstly, there's a warning you can turn on to pick up these issues. I think it's "sign comparison", the command line flag is -Wsign-compare.

If you want to iterate over the elements of an array but you need the index, the neatest way (in my opinion) is -enumerateObjectsUsingBlock:

[myArray enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) 
    NSlog(@"Object at index %lu is %@", (unsigned long) idx, obj);
    if (idx > 0)
        NSlog(@"Previous object is %@", [myArray objectAtIndex: idx - 1]);
    if (idx + 1 < [myArray count])
        NSlog(@"Next object is %@", [myArray objectAtIndex: idx + 1]);

You can still using the index while doing fast enumeration, just do:

for (id object in myArray)
    NSInteger anIndex=[myArray indexOfObject:object];

As per my suggestion, You can go with Antonio MG answer

And you want loop then try the below code

   int totalObj = myArray.count-1;
for (int i = 0; i<totalObj; i++) {
    // Write your code

JeremyP's answer is the best. If for some reason you don't want to use fast enumeration to run though the for loop, one suggestion is to just learn to use unsigned integers for your indices.

for (NSUInteger i = 0; i < something.count; i++) {

Need Your Help

Closing child window minimizes parent

wpf dialog window minimize

The following code demonstrates an issue I'm having where closing a child window minimizes the parent window, which I dont want to happen.

Jquery Script Not Causing Any Interaction

javascript jquery ajax

I have a jquery script that I just wrote up real fast to fill up a p class so that options for server interaction can be easily switched from player to server etc