如果>为什么这很简单声明不正常?

时间:2012-02-04 13:48:22

标签: iphone objective-c

这是代码:

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

输出:

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

为什么会发生这种情况?如果它是一个负数,它应该是0。

2 个答案:

答案 0 :(得分:2)

这是因为[self.icons count];返回NSUInteger(索引转换为unsigned int,将转换为UINT_MAX-3)。将其更改为以下内容:

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

答案 1 :(得分:1)

-[NSArray count]返回无符号整数。它可能会将你的-4转换为unsigned int,这是一个非常大的数字。这比三个大,所以该语句被触发,并将其设置为3.试试这个:

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

这可以避免演员阵容,并且更加清洁。