【问题标题】:Comparing NSInteger and NSUInteger比较 NSInteger 和 NSUInteger
【发布时间】: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


【解决方案1】:

这是我通过将unsigned long 转换为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;
    }
}

【讨论】:

  • 这实际上并不能解决您的问题。问题不在于强制转换,而在于 indexPath.row 是一个 NSInteger,当您将负数传递给它时,该值就会溢出。即使这在有限的情况下有效,代码也不正确,并且如果将来任何情况发生变化,也可能会中断。
猜你喜欢
  • 2014-03-17
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 2015-10-26
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多