Reputation: 16051
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
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
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