Fahim Parkar Fahim Parkar - 17 days ago 7
iOS Question

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

I have below.

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


This is giving me result as below.

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


I was expected to say

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


Any idea why this is going wrong?

Answer

this may help you to understand:

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 is unsigned (NSUInteger) and if you do a -1 operation you'll get a very big positive number, that is always bigger than 0.

that's the log:

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

if you need a signed int, use this instead:

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