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 NSInteger is a safe way to reference an integer in either a 64-bit or 32-bit environment so why use int at all?

推荐答案

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.

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

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

Ios相关问答推荐

如何仅在TextField中的文本发生更改时才执行代码?

在选项卡内列出导航内视图断开导航标题的动画

如何修复使用EFCore和SQLite的.Net MAUI iOS应用程序上的当前应用程序不支持NullabilityInfoContext?

如何在将EXPO更新到50.0后修复react 本机错误

磁盘上的Objective-C ISA指针与实例化对象时的比较

OBJC @selector 在另一个实现中不起作用

如何使用 Rxswift 处理程序最喜欢的按钮

如何在 SwiftUI 中将选项卡放在滚动视图中?

Swiftui为什么在点击第二行之前背景不起作用

TextField 重复输入 SwiftUI

SwiftUI - 在ForEach的每个元素之间自动添加分隔符

Xcode 14 弃用了位码 - 但为什么呢?

通过MatchedGeometryEffect向上滑动视图

UIScrollview 获取touch 事件

Xcode 4 + iOS 4.3:存档类型不存在打包程序

SRCROOT 和 PROJECT_DIR 有什么区别?

无法加载从带有标识符的包中的笔尖引用的图像

测试目标 X 遇到错误(提前意外退出,操作从未完成 bootstrap - 不会try 重新启动

如何在 iOS 中获取正在运行的应用程序的名称

在 iOS 上没有显示数字键盘