I have an unsigned int variable and it can only have the values of 0 -> 30. What should I use: unsigned int or NSUInteger? (for both 32 and 64 bit)
A:
It makes very little difference in your case, there is no right or wrong. I might use an NSUInteger, just to match with Cocoa API stuff.
NSUInteger is 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
invariant
2010-04-03 09:09:55
Thanks. So on 64 bit my NSUInteger will be an unsigned long right? Doesn't that occupy twice as much memory as just using int?
Michael Matheus
2010-04-03 09:27:41
Yes, that's right. A `long` will be 8 bytes and an `int` will be 4 bytes, on a 64 bit target. On 32-bit, `int` and `long` are the same.
invariant
2010-04-03 09:56:26
A:
krasnyk
2010-04-03 09:12:03
Thanks. So on 64 bit my NSUInteger will be an unsigned long right? Doesn't that occupy twice as much memory as just using int?
Michael Matheus
2010-04-03 09:28:03
A:
Running this:
int sizeLong = sizeof(unsigned long);
int sizeInt = sizeof(unsigned int);
NSLog(@"%d, %d", sizeLong, sizeInt);
on 64bits gives:
8, 4
on 32 bits gives:
4, 4
So that yes, on 64 bits unsigned long (NSUInteger) takes twice as much memory as NSUInteger on 32 bits.
krasnyk
2010-04-03 10:08:49
+2
A:
I’d go with either NSUInteger
(as the idiomatic general unsigned integer type in Cocoa) or uint8_t
(if size matters). If I expected to be using 0–30 values in several places for the same type of data, I’d typedef it to describe what it represents.
Ahruman
2010-04-03 11:14:10
+1 for thinking about what's most theoretically correct instead of just how many bytes will be wasted.
andyvn22
2010-04-03 14:56:28