iOS:NSInteger和NSUInteger比较

时间:2014-08-25 06:50:29

标签: ios objective-c comparison nsinteger nsuinteger

惊喜!

我有一个像这样的变量,

NSInteger index = 0;

我将它与其中一个子视图count(返回NSUInteger)进行比较,

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

这总是假的。

但如果我这样做,

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

这总是真的。

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

当我有一个基于这种逻辑的工作解决方案时,我发现了这个问题。 但它根本不是真的。

1 个答案:

答案 0 :(得分:5)

我发现了这个,NSUInteger vs NSInteger, int vs unsigned, and similar cases

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


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

以下片段例如返回0(false),但您希望它打印1(true):

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

原因是[si]变量被隐式转换为unsigned int!

请参阅CERT's Secure Coding site,深入讨论这些问题&#39;以及如何解决它们。