int和NSInteger有什么区别?

Pra*_*sad 14 int cocoa types objective-c nsinteger

可能重复:
何时使用NSInteger vs int?
为什么有NSInteger?

我们可以使用intNSInteger互换吗?是否有任何具体情况只能使用NSInteger,而不是使用int

Jer*_*myP 20

我们可以互换使用int和NSInteger吗?

在Apple使用的LP64架构上,对于现代OS X Cocoa,NSInteger是64位宽.这意味着如果将NSInteger转换为int,则与NSNotFound的比较可能会失败.这是一个例子:

NSRange theRange = [@"foo" rangeOfString @"x"];
int location = theRange.location;
if (location == NSNotFound) // comparison is broken due to truncation in line above
{
    // x not in foo
}
Run Code Online (Sandbox Code Playgroud)

在我看来,你应该只使用NSInteger你需要的地方将参数传递给Cocoa或从Cocoa接收结果,文档说数据类型是NSInteger.在所有其他情况下:

  • 如果您不关心类型的宽度,请使用C类型,例如intlong.
  • 如果您关心类型的宽度,请使用C99 stdint.h类型,例如int32_t,int64_t.
  • 如果你需要一个足以保持指针的int,请使用intptr_tuintptr_t