@property (nonatomic, assign) int user_id;
可以注意到 apple 的 UIKit 等代码一般都是用的 NSInteger。NSInteger 在 32位系统是 int ,64位系统是 long 。Apple 把它用在函数的参数处,和返回的地方。为什么?因为函数是需要跟其它代码或其它平台的代码交流互动的,所以是 int 还是 long 很重要。系统的代码用的是 NSInteger 的话,你的用了 int 的话,可能不够大而造成崩溃。
这里可参考 Stack Overflow 的一个详细讨论。《什么时候用 NSInteger 和 int ?》。
When to use NSInteger vs. int
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;...
But within a function they’re just using int to track a value
for (int i; i < something; i++)
...
int something;
something += somethingElseThatsAnInt;
...
I’ve read (been told) that` NSIntege is a safe way to reference an integer in either a 64-bit or 32-bit environment so why use int at all?
Answers
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.
I’d stick with using NSInteger
instead of int/long
unless you specifically require them.
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