Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 960
Shizam Avatar asked Dec 14 '10 23:12

Shizam


People also ask

Is int always 32 bits?

int is always 32 bits wide. sizeof(T) represents the number of 8-bit bytes (octets) needed to store a variable of type T . (This is false because if say char is 32 bits, then sizeof(T) measures in 32-bit words.) We can use int everywhere in a program and ignore nuanced types like size_t , uint32_t , etc.

What is NSInteger?

NSInteger is a type definition that describes an integer - but it is NOT equivalent to int on 64-bit platforms. You can examine the typedef by cmd-clicking on NSInteger in Xcode. NSInteger is defined as int when building a 32-bit app and as long for 64-bit apps.

What is NSNumber in Swift?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .


1 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 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

like image 96
Jacob Relkin Avatar answered Oct 06 '22 15:10

Jacob Relkin