madewulf
madewulf

Reputation: 1910

Objective-c, strange behaviour when iterating over an empty NSArray

I don't understand what is happening with this piece of code:

The sortedArray, which is a NSMutableArray, is empty, so, the value of sortedArray.count is 0.

     for (NSUInteger i = 0 ; i < (sortedArray.count -1) ; i++) 
         NSLog(@"Apparently %d < %d  ( [sortedArray count] %d)", i, sortedArray.count-1, [sortedArray count] );

Consequently, we should never enter the loop, but I see the following in the log:

2014-01-21 12:11:16.433 AppName[445:60b] Apparently 0 < -1 ( [sortedArray count] 0)

Does anybody has an idea of what can trigger the problem?

Upvotes: 1

Views: 135

Answers (3)

Greg
Greg

Reputation: 25459

The issue is in your logic your condition should be:

for (NSUInteger i = 0 ; i <= (sortedArray.count -1) ; i++) 

or

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

In your example you subtract 1 from zero which gives you -1 so -1 is less that (sortedArray.count -1) so the condition is true and it enters to the loop.

Upvotes: 0

Wain
Wain

Reputation: 119031

You can (and should) just use:

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

because the test i < sortedArray.count will return NO as 0 is not less than 0. You current code, if the array had content, would not iterate the last object in the array.

Upvotes: 0

John Estropia
John Estropia

Reputation: 17500

(sortedArray.count -1)

is an unsigned integer 0 trying to subtract one from itself, so your -1 is being interpreted as NSUIntegerMax

Upvotes: 5

Related Questions