【发布时间】:2018-07-05 13:52:52
【问题描述】:
我需要比较两个变量,以检查数组中是否存在索引:
indexPath.row 是 NSInteger
[self arrayOfData].count 是 NSUInteger
问题是它们属于不同的类型,当indexPath.row=-1 时,它会自动转换为 18446744073709551615(无符号长整数),这是我要避免的。
如何检查NSIndexPath 的行定义的索引是否存在于NSArray 中?
代码:
- (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;
}
}
【问题讨论】:
-
如果你知道你不会得到这么高的价值,那就投吧?
-
@Larme 是的,现在可以使用了。
-
你如何以负 indexPath.row 值结束?是您自己设置还是通过 Apple API 以这种方式提供给您?
-
@NimaYousefi 我自己设置它以指示未选择索引或基础数组中不存在数据
-
我通常不建议这样做,但如果你想以这种方式使用它,我建议设置
indexPath.row = NSNotFound,这是一个全局 NSInteger 值,你可以在这种情况下使用它。它被 Apple 广泛用于 NSRange,它也需要 NSIntegers。然后只需在代码中检查此条件,而不是对照数组计数。 developer.apple.com/documentation/foundation/…
标签: objective-c nsarray nsindexpath nsinteger nsuinteger