enum values: NSInteger or int? enum values: NSInteger or int? objective-c objective-c

enum values: NSInteger or int?


There is now NS_ENUM starting Xcode 4.5:

typedef NS_ENUM(NSUInteger, NSCellType) {    NSNullCellType = 0,    NSTextCellType = 1,    NSImageCellType = 2};

And you can consider NS_OPTIONS if you work with binary flags:

typedef NS_OPTIONS(NSUInteger, MyCellFlag) {    MyTextCellFlag = 1 << 0,    MyImageCellFlag = 1 << 1,};


I run a test on the simulator so the intention of the test is check the size of different integer types. For that, the result of sizeof was printed in the console. So I test this enum values:

      typedef enum {    TLEnumCero = 0,    TLEnumOne = 1,    TLEnumTwo = 2} TLEnum;typedef enum {    TLEnumNegativeMinusOne = -1,    TLEnumNegativeCero = 0,    TLEnumNegativeOne = 1,    TLEnumNegativeTwo = 2} TLEnumNegative;typedef NS_ENUM(NSUInteger, TLUIntegerEnum) {    TLUIntegerEnumZero = 0,    TLUIntegerEnumOne = 1,    TLUIntegerEnumTwo = 2};typedef NS_ENUM(NSInteger, TLIntegerEnum) {    TLIntegerEnumMinusOne = -1,    TLIntegerEnumZero = 0,    TLIntegerEnumOne = 1,    TLIntegerEnumTwo = 2};

Test Code:

    NSLog(@"sizeof enum: %ld", sizeof(TLEnum));    NSLog(@"sizeof enum negative: %ld", sizeof(TLEnumNegative));    NSLog(@"sizeof enum NSUInteger: %ld", sizeof(TLUIntegerEnum));    NSLog(@"sizeof enum NSInteger: %ld", sizeof(TLIntegerEnum));

Result for iPhone Retina (4-inch) Simulator:

sizeof enum: 4sizeof enum negative: 4sizeof enum NSUInteger: 4sizeof enum NSInteger: 4

Result for iPhone Retina (4-inch 64 bit) Simulator:

sizeof enum: 4sizeof enum negative: 4sizeof enum NSUInteger: 8sizeof enum NSInteger: 8

Conclusion

A generic enum can be an int or unsigned int types of 4 bytes for 32 or 64 bits.As we already know NSUInteger and NSInteger are 4 bytes for 32 bits and 8 bytes in 64 bits compiler for iOS.


These are two separate declarations. The typedef guarantees that, when you use that type, you always get an NSUInteger.

The problem with an enum is not that it's not large enough to hold the value. In fact, the only guarantee you get for an enum is that sizeof(enum Foo) is large enough to hold whatever values you've currently defined in that enum. But its size may change if you add another constant. That's why Apple do the separate typedef, to maintain binary stability of the API.