Convert objective-c typedef to its string equivalent Convert objective-c typedef to its string equivalent objective-c objective-c

Convert objective-c typedef to its string equivalent


This is really a C question, not specific to Objective-C (which is a superset of the C language). Enums in C are represented as integers. So you need to write a function that returns a string given an enum value. There are many ways to do this. An array of strings such that the enum value can be used as an index into the array or a map structure (e.g. an NSDictionary) that maps an enum value to a string work, but I find that these approaches are not as clear as a function that makes the conversion explicit (and the array approach, although the classic C way is dangerous if your enum values are not continguous from 0). Something like this would work:

- (NSString*)formatTypeToString:(FormatType)formatType {    NSString *result = nil;    switch(formatType) {        case JSON:            result = @"JSON";            break;        case XML:            result = @"XML";            break;        case Atom:            result = @"Atom";            break;        case RSS:            result = @"RSS";            break;        default:            [NSException raise:NSGenericException format:@"Unexpected FormatType."];    }    return result;}

Your related question about the correct syntax for an enum value is that you use just the value (e.g. JSON), not the FormatType.JSON sytax. FormatType is a type and the enum values (e.g. JSON, XML, etc.) are values that you can assign to that type.


You can't do it easily. In C and Objective-C, enums are really just glorified integer constants. You'll have to generate a table of names yourself (or with some preprocessor abuse). For example:

// In a header filetypedef enum FormatType {    JSON,    XML,    Atom,    RSS} FormatType;extern NSString * const FormatType_toString[];// In a source file// initialize arrays with explicit indices to make sure // the string match the enums properlyNSString * const FormatType_toString[] = {    [JSON] = @"JSON",    [XML] = @"XML",    [Atom] = @"Atom",    [RSS] = @"RSS"};...// To convert enum to string:NSString *str = FormatType_toString[theEnumValue];

The danger of this approach is that if you ever change the enum, you have to remember to change the array of names. You can solve this problem with some preprocessor abuse, but it's tricky and ugly.

Also note that this assumes you have a valid enum constant. If you have an integer value from an untrusted source, you additionally need to do a check that your constant is valid, e.g. by including a "past max" value in your enum, or by checking if it's less than the array length, sizeof(FormatType_toString) / sizeof(FormatType_toString[0]).


My solution:

edit: I've added even a better solution at the end, using Modern Obj-C

1.
Put names as keys in an array.
Make sure the indexes are the appropriate enums, and in the right order (otherwise exception).
note: names is a property synthesized as *_names*;

code was not checked for compilation, but I used the same technique in my app.

typedef enum {  JSON,  XML,  Atom,  RSS} FormatType;+ (NSArray *)names{    static NSMutableArray * _names = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _names = [NSMutableArray arrayWithCapacity:4];        [_names insertObject:@"JSON" atIndex:JSON];        [_names insertObject:@"XML" atIndex:XML];        [_names insertObject:@"Atom" atIndex:Atom];        [_names insertObject:@"RSS" atIndex:RSS];    });    return _names;}+ (NSString *)nameForType:(FormatType)type{    return [[self names] objectAtIndex:type];}


//

2.
Using Modern Obj-C you we can use a dictionary to tie descriptions to keys in the enum.
Order DOES NOT matter.

typedef NS_ENUM(NSUInteger, UserType) {    UserTypeParent = 0,    UserTypeStudent = 1,    UserTypeTutor = 2,    UserTypeUnknown = NSUIntegerMax};  @property (nonatomic) UserType type;+ (NSDictionary *)typeDisplayNames{    return @{@(UserTypeParent) : @"Parent",             @(UserTypeStudent) : @"Student",             @(UserTypeTutor) : @"Tutor",             @(UserTypeUnknown) : @"Unknown"};}- (NSString *)typeDisplayName{    return [[self class] typeDisplayNames][@(self.type)];}


Usage (in a class instance method):

NSLog(@"%@", [self typeDisplayName]);