本文介绍了NSUInteger vs NSInteger,int和unsigned,以及类似的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都有专业知识解释什么时候使用NSUInteger和什么时候使用NSInteger?

Anyone have the expertise to explain when to use NSUInteger and when to use NSInteger?

我曾经看过Cocoa方法返回NSInteger甚至在返回值总是未签名。

I had seen Cocoa methods returning NSInteger even in cases where the returned value will always be unsigned.

基本原因是什么?如果我们想要表示负值,那么NSInteger或int是否严格限制?

What is the fundamental reason? Is NSInteger or int strictly limited to if we want to represent negative value?

来自NSObjCRuntime.h:

From NSObjCRuntime.h:

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif


推荐答案

处理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]变量被隐式转换为unsigned int!

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

请参阅,以深入讨论这些问题以及如何解决这些问题。

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

这篇关于NSUInteger vs NSInteger,int和unsigned,以及类似的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 13:29