String enums in Objective-C

Note: I have written a newer and better solution to this problem in a new video, which you can watch by clicking here.

Sooo a lot of programmers think enumeration items cannot be strings, and they are right, BUT, there is a BUT. You have to understand that C strings that are made out of 4 characters, each of which is 1 byte long, constitute a memory address that is 4 bytes long, or just the equivalent of int, NSInteger or whatever you want to call it.

So if you put a value such as ‘Good’ for the enumeration item, in fact, the compiler will translate the values of ‘G’, ‘o’, ‘o’ and ‘d’ as their numerical values and will generate a hexadecimal value and put it as the integral value of the enumeration item.

Let’s say we want to say “Good”, or “Nice” all in enumeration items in C. Here is the example, this code runs fine in Objective-C for iOS or OS X as well:

Screen Shot 2013-03-24 at 19.30.24

The output of this is the string “dooG” printed to the screen if you run this on an iPhone device for instance. The reason is the bytes are obviously reversed as the string ‘Good’ has the letter ‘d’ as the lowest byte and that ends up being at the first byte of the string so we end up with “dooG”. That’s not good though, is it? So we just have to swap the bytes around to get the proper string:

Screen Shot 2013-03-24 at 19.31.08

Easy peasy, aye? The highlighted line is very important. That line swaps the order of bytes in the integer. Also note that I am using the calloc function as it will not only allocate the memory but also set the byte values to 0×00 in the memory for us so we don’t have to do it manually or with another procedure.

About these ads