Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum Values to NSString (iOS)

I have an enum holding several values:

enum {value1, value2, value3} myValue;

In a certain point in my app, I wish to check which value of the enum is now active. I'm using NSLog but I'm not clear on how to display the current value of the enum (value1/valu2/valu3/etc...) as a NSString for the NSLog.

Anyone?

like image 808
Ohad Regev Avatar asked Jun 13 '11 14:06

Ohad Regev


2 Answers

I didn't like putting the enum on the heap, without providing a heap function for translation. Here's what I came up with:

typedef enum {value1, value2, value3} myValue; #define myValueString(enum) [@[@"value1",@"value2",@"value3"] objectAtIndex:enum] 

This keeps the enum and string declarations close together for easy updating when needed.

Now, anywhere in the code, you can use the enum/macro like this:

myValue aVal = value2; NSLog(@"The enum value is '%@'.", myValueString(aVal));  outputs: The enum value is 'value2'. 

To guarantee the element indexes, you can always explicitly declare the start(or all) enum values.

enum {value1=0, value2=1, value3=2}; 
like image 192
Mark Longmire Avatar answered Oct 22 '22 13:10

Mark Longmire


This is answered here: a few suggestions on implementation

The bottom line is Objective-C is using a regular, old C enum, which is just a glorified set of integers.

Given an enum like this:

typedef enum { a, b, c } FirstThreeAlpha; 

Your method would look like this:

- (NSString*) convertToString:(FirstThreeAlpha) whichAlpha {     NSString *result = nil;      switch(whichAlpha) {         case a:             result = @"a";             break;         case b:             result = @"b";             break;         case c:             result = @"c";             break;          default:             result = @"unknown";     }      return result; } 
like image 20
badMonkey Avatar answered Oct 22 '22 15:10

badMonkey