nsmutablearray.count 和 tableview indexpath.row 之间的比较给出了奇怪的结果

comparision between nsmutablearray.count & tableview indexpath.row is giving odd results

下面有。

NSLog(@"aaaa===%ld==%ld", indexPath.row, (rowsOptionss.count-1));

if (indexPath.row>(rowsOptionss.count-1)) {
    NSLog(@"000===this is true");
} else {
    NSLog(@"000===this is false");
}

if (0>-1) {
    NSLog(@"001===this is true");
} else {
    NSLog(@"001===this is false");
}

结果如下。

2016-02-04 13:02:15.316 ClubsFans[7085:16944474] aaaa===0==-1
2016-02-04 13:02:15.316 ClubsFans[7085:16944474] 000===this is false
2016-02-04 13:02:15.316 ClubsFans[7085:16944474] 001===this is true

我应该说

2016-02-04 13:02:15.316 ClubsFans[7085:16944474] aaaa===0==-1
2016-02-04 13:02:15.316 ClubsFans[7085:16944474] 000===this is true >> this should be true
2016-02-04 13:02:15.316 ClubsFans[7085:16944474] 001===this is true

知道为什么会出错吗?

@Fahim Parkar

请尝试将 NSInteger 转换为 Int。这可能导致比较 NSInteger.

if((int) indexPath.row > (int)(rowsOptionss.count-1))

希望对您有所帮助。

这可能有助于您理解:

NSIndexPath* indexPath = nil;
NSArray * rowsOptionss = [NSArray array];
NSLog(@"aaaa===%ld==%ld", indexPath.row, (rowsOptionss.count-1));
NSLog(@"real value: bbbb===%ld==%u", (long)indexPath.row, (rowsOptionss.count-1));

if (indexPath.row>(rowsOptionss.count-1)) {
    NSLog(@"000===this is true");
} else {
    NSLog(@"000===this is false");
}

if (0>-1) {
    NSLog(@"001===this is true");
} else {
    NSLog(@"001===this is false");
}

rowsOptionss.count 是无符号的 (NSUInteger),如果您执行 -1 操作,您将得到一个非常大的正数,它总是大于 0。

这是日志:

 aaaa===0==-1
 real value: bbbb===0==4294967295
 000===this is false
 001===this is true

如果您需要一个带符号的整数,请改用它:

NSInteger tempInt = rowsOptionss.count;
tempInt --;
LOG(@"tempInt %i", tempInt);