2016-02-04 76 views
1

我有下面。nsmutablearray.count和tableview indexpath.row之間的比較給出了奇怪的結果

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 

知道爲什麼這是怎麼了?

+1

無符號整數下溢。使用無符號整數時,添加比減去例如總是更安全。 'indexPath.row + 1 Sulthan

回答

5

這可能會幫助您瞭解:

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

我推薦使用'「%@」'和'@(rowsOptionss.count-1)來打​​印整數數字) – Sulthan

0

@Fahim Parkar

請嘗試轉換從NSInteger的詮釋。這可能會導致比較NSInteger

IF((INT)indexPath.row>(INT)(rowsOptionss.count-1))

希望這會幫助你。