0

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;
    }
}
Peter G.
  • 7,816
  • 20
  • 80
  • 154
  • 2
    If you know you won't get such a high value, cast it? – Larme Jul 05 '18 at 13:56
  • @Larme yes, it works now. – Peter G. Jul 05 '18 at 14:00
  • How are you ending up with a negative indexPath.row value? Are you setting it yourself or is it coming to you that way from an Apple API? – Nima Yousefi Jul 05 '18 at 19:25
  • @NimaYousefi I'm setting it myself to indicate that no index was selected or no data are present in the underlying array – Peter G. Jul 06 '18 at 08:47
  • I would generally recommend against that, but if you want to use it this way I would recommend setting `indexPath.row = NSNotFound`, which is a global NSInteger value you can use for situations like this. It's used extensively by Apple with NSRange, which also requires NSIntegers. Then just check for this condition in your code instead of against the array count. https://developer.apple.com/documentation/foundation/nsnotfound?language=objc – Nima Yousefi Jul 06 '18 at 16:09

1 Answers1

0

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;
    }
}
Peter G.
  • 7,816
  • 20
  • 80
  • 154
  • This doesn't actually solve your problem. The problem isn't the casting, it's that indexPath.row is an NSInteger, and when you pass a negative number to it the value is blown out. Even if this works in a limited case, the code isn't correct and is likely to break if any circumstances change in the future. – Nima Yousefi Jul 06 '18 at 16:19