开发者

Puzzling: If statement with <= not working as expected

开发者 https://www.devze.com 2023-03-17 14:57 出处:网络
This is probably obvious, but I cannot see it... NSLog(@\"nthObject = %i, [mutableFetchResults count] - 1 = %i\", nthObject, [mutableFetchResults count] - 1);

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 shou开发者_JAVA百科ld 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.


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])


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...


[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.


[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).

0

精彩评论

暂无评论...
验证码 换一张
取 消