Comparing NSInteger and NSUInteger

407 Views Asked by At

I have two variables that I need to compare, in order to check if an index exists in an array: indexPath.row is NSInteger [self arrayOfData].count is NSUInteger

The problem is that they are of different types and when indexPath.row=-1 it gets automatically converted to 18446744073709551615 (unsigned long), which is what I'm trying to avoid.

How do I check if an index defined by NSIndexPath's row exists in an NSArray?

Code:

- (void) checkIfIndexExists:(NSIndexPath*) indexPath inArray:(NSArray*)arrayOfData {
    if (indexPath.row >= [self arrayOfData].count) {  // indexPath.row=-1 gets interpretted as 18446744073709551615 (unsigned long)
        DDLogDebug(@"Warning: Index doesn't exist {%@}", indexPath);
        return;
    }
}
1

There are 1 best solutions below

1
Peter G. On

Here is how I solved the problem by casting unsigned long to long

- (void) checkIfIndexExists:(NSIndexPath*) indexPath inArray:(NSArray*)arrayOfData {
    if (indexPath.row >= (long) [self arrayOfData].count) {  // indexPath.row=-1 gets interpretted as 18446744073709551615 (unsigned long)
        DDLogDebug(@"Warning: Index doesn't exist {%@}", indexPath);
        return;
    }
}