【问题标题】:iOS : NSInteger and NSUInteger comparisoniOS:NSInteger 和 NSUInteger 比较
【发布时间】:2014-10-18 06:41:49
【问题描述】:

惊喜!

我有一个这样的变量,

NSInteger index = 0;

我将它与这样的子视图计数之一(返回NSUInteger)进行比较,

if((index-1) <= [[currentmonth subviews] count]) 
{
    NSLog(@"true");
}
else
{
    NSLog(@"false");
}

这总是假的。

但如果我这样做,

if ((index-1) <= 42) {
    NSLog(@"true");
} else {
    NSLog(@"false");
}

这总是真实的。

我觉得,这是因为我们无法将NSIntegerNSUInteger 进行比较,对吗?

当我有一个基于此逻辑的可行解决方案时,我发现了这个问题。 但事实并非如此。

【问题讨论】:

    标签: ios objective-c comparison nsinteger nsuinteger


    【解决方案1】:

    我找到了这个,NSUInteger vs NSInteger, int vs unsigned, and similar cases

    这个答案给出了很好的解释!


    在处理 NSUInteger 与 NSInteger 时,您还应该注意整数转换规则:

    例如,以下片段返回 0(假),尽管您希望它打印 1(真):

    NSInteger si = -1;
    NSUInteger ui = 1;
    printf("%d\n", si < ui);
    

    原因是 [si] 变量被隐式转换为无符号整数!

    请参阅CERT's Secure Coding site,以深入讨论这些“问题”以及如何解决这些问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      相关资源
      最近更新 更多