Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSInteger vs 64-bit architecture on iOS

Tags:

ios

So, I'm trying to figure out how much I should care about NSInteger vs int. I don't have a CS degree, so a lot of these type conversion arguments come across pretty obscure. As best I can tell, the argument is "use NSInteger instead of int in iOS so that eventually if/when 64-bit iOS comes out, your variables will still be the right size to store a pointer." Fair enough. Except I'm storing pointers in my ints approximately never.

Suppose I have an int storing a count of magic beans owed to Jack, and another int storing the number of ways to skin a cat, and I'm passing them between functions and writing them to Core Data and whatever, and then Apple releases 64-bit iOS -- what changes? Why do I care?

Also, if I do care, why isn't that an argument for using int32_t instead of NSInteger? It seems like that would be the way to keep things predictable.

like image 854
c roald Avatar asked May 28 '13 19:05

c roald


2 Answers

Your point about using types from the <stdint.h> header of C99 is absolutely valid: these types give you more control over the size of your integral types. The NS-prefixed integral types, however, predate the standardization of <stdint.h>, hence introducing a parallel set of abstractions.

I use NS-prefixed integral types when interacting with Cocoa methods. For example, if Cocoa method returns NSUinteger, I declare my variable using NSUinteger type as well.

I use <stdint.h> types for variables in my program when I need precise control over the size of the stored data. Items that end up in Core Data are in this category.

When the size of an integral type does not matter, for example, when I need a loop control variable in a for loop, I use int.

like image 71
Sergey Kalinichenko Avatar answered Oct 20 '22 03:10

Sergey Kalinichenko


My recommendation:

  • When writing Obj-C code, use NSInteger. It then conforms to the frameworks you use. It might change once from int to something else (int64_t, long, ?).

  • If writing C/C++ code (portability) obviously don't use NSInteger.

If you think your variable will exceed INT_MAX (a const. check here) you might use int64_t (when you like to have 32/64 bit flexible code) or long (if you don't share memory objects between 32/64 bit versions of your app). Also consider using unsigned types (uint uint64_t) when you are sure not having minus values in your vars.

Internally: for pointers, don't use int. use void *

like image 21
Jonas Schnelli Avatar answered Oct 20 '22 03:10

Jonas Schnelli