craig craig - 1 year ago 97
Objective-C Question

Convert objective-c typedef to its string equivalent

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

typedef enum {
} 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 Source

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";
        case XML:
            result = @"XML";
        case Atom:
            result = @"Atom";
        case RSS:
            result = @"RSS";
            [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.