Convert objective-c typedef to its string equivalent

craig picture craig · Jul 7, 2009 · Viewed 130.4k times · Source

Assuming that I have a typedef declared in my .h file as such:

typedef enum {
  JSON,
  XML,
  Atom,
  RSS
} FormatType;

I would like to build a function that converts the numeric value of the typedef to a string. For example, if the message [self toString:JSON] was sent; it would return 'JSON'.

The function would look something like this:

-(NSString *) toString:(FormatType)formatType {
  //need help here
  return [];
}

Incidentally, if I try this syntax

[self toString:FormatType.JSON];

to pass the typedef value to the method, I get an error. What am I missing?

Answer

Barry Wark picture Barry Wark · Jul 7, 2009

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.