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

查看:33
本文介绍了何时使用 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,所以你可以出于某种原因,需要最大可能的整数类型,在 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 integer 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天全站免登陆