本文介绍了iOS:NSInteger和NSUInteger的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

惊喜!

我有一个这样的变量

NSInteger index = 0;

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

I'm comparing it with one of subviews count (which returns NSUInteger) like this,

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

但是如果我愿意这样做的话,

but If I'll do like this,

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

我认为,这是因为我们无法将 NSInteger NSUInteger 比较正确吗?

I feel that, this because we can't compare NSInteger with NSUInteger correct?

当我有一个基于此逻辑的可行解决方案时,我抓住了这个问题. 但这不是真的.

I caught this issue, when I have a working solution based on this logic. But its not true at all.

推荐答案

我已经找到了这个

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

This answer gives the good explanations on this!

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

You should also be aware of integer conversion rules when dealing with NSUInteger vs. NSInteger:

例如,以下片段返回0(false),尽管您希望它显示1(true):

The following fragment for example returns 0 (false) although you'd expect it to print 1 (true):

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

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

The reason is that the [si] variable is being implicitly converted to an unsigned int!

请参见 CERT的安全编码网站,以深入讨论这些问题"以及如何解决这些问题.

See CERT's Secure Coding site for an in-depth discussion around these 'issues' and how to solve them.

这篇关于iOS:NSInteger和NSUInteger的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 00:03