Andrew
Andrew

Reputation: 16051

Why is this simple if > statement not working correctly?

This is the code:

int index = (gridPoint.y * self.iconsPerRow) + gridPoint.x;
    NSLog(@"index 1: %i", index);
    NSLog(@"count: %i", [self.icons count] - 1);
    if (index > [self.icons count] - 1) {
        index = [self.icons count] - 1;
    }
    if (index < 0) {
        index = 0;
    }
    NSLog(@"index 2: %i", index);

Output:

NSLog index 1: -4
NSLog count: 3
NSLog index 2: 3

Any ideas why this is happening? It should be resulting in 0 if it's a minus number.

Upvotes: 0

Views: 88

Answers (2)

Ben Gottlieb
Ben Gottlieb

Reputation: 85542

-[NSArray count] returns an unsigned integer. It's probably converting your -4 to an unsigned int, which is a VERY big number. That's bigger than three, so that statement is getting triggered, and setting it to 3. Try this:

if (index >= self.icons.count) {
    ...
} 

This avoids the cast, and is a little cleaner.

Upvotes: 1

jrtc27
jrtc27

Reputation: 8536

It's because [self.icons count]; returns an NSUInteger (index is converted to an unsigned int, which will wrap around to UINT_MAX-3). Change it to the following:

int index = (gridPoint.y * self.iconsPerRow) + gridPoint.x;
NSLog(@"index 1: %i", index);
NSLog(@"count: %i", [self.icons count] - 1);
if (index < 0) {
    index = 0;
} else if (index + 1 > [self.icons count]) { // In case count is 0, we add to index rather than subtract from count
    index = [self.icons count] - 1;
}
NSLog(@"index 2: %i", index);

Upvotes: 2

Related Questions