int和NSInteger有什么区别? [英] What is the difference between int and NSInteger?

查看:127
本文介绍了int和NSInteger有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

何时使用NSInteger vs int?

为什么有NSInteger?

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

Can we use int and NSInteger interchangably? Is there any specific situation to use NSInteger only, instead of using int?

推荐答案


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

Can we use int and NSInteger interchangably?

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

No. On the LP64 architecture used by Apple, for modern OS X Cocoa, NSInteger is 64 bits wide. This means that if you cast an NSInteger to an int, comparisons against NSNotFound may fail. Here's an example:

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
}

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

In my opinion, you should only use NSInteger where you need to pass a parameter to Cocoa or receive a result from Cocoa and the documentation says the data type is NSInteger. In all other cases:


  • 如果您不关心类型的宽度,请使用C类型,例如: int long

  • 如果你关心的是宽度输入类型,使用C99 stdint.h 类型,例如 int32_t int64_t

  • 如果你需要一个足够大的int来保存指针,请使用 intptr_t uintptr_t

  • if you don't care about the width of the type, use a C type e.g. int or long.
  • if you do care about the width of the type, use the C99 stdint.h types e.g. int32_t, int64_t.
  • if you need an int guaranteed big enough to hold a pointer, use intptr_t or uintptr_t

这篇关于int和NSInteger有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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