Chris
Chris

Reputation: 1475

Puzzling: If statement with <= not working as expected

This is probably obvious, but I cannot see it...

NSLog(@"nthObject = %i, [mutableFetchResults count] - 1 = %i", nthObject, [mutableFetchResults count] - 1);
if (nthObject <= [mutableFetchResults count] - 1) {
    MyObject *myObject = [mutableFetchResults objectAtIndex:nthObject];

The count of mutableFetchResults is zero, so [mutableFetchResults count] - 1 = -1 and nthObject is 0. This is proven by the Log.

nthObject is an int passed into the method.

So the of statement should be saying if (0 <= -1) and therefore not firing the MyObject *myObject = [mutableFetchResults objectAtIndex:nthObject] line, but it does which then causes a crash as its trying to access an empty array.

Any ideas?

Many thanks,

Chris.

Upvotes: 1

Views: 98

Answers (4)

Michael Burr
Michael Burr

Reputation: 340188

I'm assuming that mutableFetchResults is an NSMutableArray (a subclass of NSArray). The count member is an NSUInteger which is unsigned, so [mutableFetchResults count] - 1 doesn't go negative - it wraps around to become a very large number.

Change your test to be:

if (nthObject < [mutableFetchResults count])

Upvotes: 8

nos
nos

Reputation: 229058

[mutableFetchResults count] likely is this, so it yields an unsigned integer. It will wrap around to the max value of an unsigned integer , and your i will also be promoted to an unsigned type.

You comparison ends up as something like (0 < 0xffffffff).

Upvotes: 1

InsertWittyName
InsertWittyName

Reputation: 3940

[mutableFetchResults count] returns an NSUInteger.

If count is 0 then 0 - 1 on an NSUInteger will not be -1, it will 'wrap' around and be a massive number.

Upvotes: 1

MRAB
MRAB

Reputation: 20654

Is [mutableFetchResults count] an unsigned int? The "%i" in the format string says to print it as a signed int, but that doesn't mean it is...

Upvotes: 2

Related Questions