何时使用NSInteger与int [英] When to use NSInteger vs. int

查看:154
本文介绍了何时使用NSInteger与int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为iOS开发时,我应该何时使用 NSInteger 与int?我在Apple示例代码中看到,当将值作为参数传递给函数时,它们使用 NSInteger (或 NSUInteger )或者从函数返回一个值。

When should I be using NSInteger vs. int when developing for iOS? I see in the Apple sample code they use NSInteger (or NSUInteger) when passing a value as an argument to a function or returning a value from a function.

- (NSInteger)someFunc;...
- (void)someFuncWithInt:(NSInteger)value;...

但在函数中他们只是使用 int 跟踪一个值

But within a function they're just using int to track a value

for (int i; i < something; i++)
...

int something;
something += somethingElseThatsAnInt;
...

我读过(被告知) NSInteger 是一种在64位或32位环境中引用整数的安全方法,那么为什么要使用 int 呢?

I've read (been told) that NSInteger is a safe way to reference an integer in either a 64-bit or 32-bit environment so why use int at all?

推荐答案

当你不知道什么样的时候,你通常想要使用 NSInteger 您的代码可能运行的处理器体系结构,因此您可能出于某种原因需要最大可能的 int 类型,这在32位系统上只是一个 int ,而在64位系统上,它是 long

You usually want to use NSInteger when you don't know what kind of processor architecture your code might run on, so you may for some reason want the largest possible int type, which on 32 bit systems is just an int, while on a 64-bit system it's a long.

我坚持使用 NSInteger 代替 int / long 除非您特别要求它们。

I'd stick with using NSInteger instead of int/long unless you specifically require them.

NSInteger / NSUInteger 被定义为* dynamic typedef * s到其中一种类型,它们的定义如下:

NSInteger/NSUInteger are defined as *dynamic typedef*s to one of these types, and they are defined like this:

#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

关于正确的格式说明符,您应该为每种类型使用,请参阅字符串编程指南中有关平台依赖性的部分

With regard to the correct format specifier you should use for each of these types, see the String Programming Guide's section on Platform Dependencies

这篇关于何时使用NSInteger与int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆