Converting between C enum and XML

前端 未结 5 373
遇见更好的自我
遇见更好的自我 2020-12-04 20:21

What\'s the cleanest way to store an enum in XML and read it back out again? Say I\'ve got:

enum ETObjectType {ETNormalObjectType, ETRareObjectType, ETEssent         


        
5条回答
  •  我在风中等你
    2020-12-04 21:06

    I echo Jon's solution, but you can use the dreaded X-macro to avoid repeating yourself at all. I don't know how to comment on Jon's answer with code formatting, so here it is as a new answer.

    #define ETObjectTypeEntries \
    ENTRY(ETNormalObjectType) \
    ENTRY(ETRareObjectType) \
    ENTRY(ETEssentialObjectType)
    
    typedef enum ETObjectType {
    #define ENTRY(objectType) objectType, 
        ETObjectTypeEntries
    #undef ENTRY
    } ETObjectType;
    
    NSString *ETObjectTypesAsStrings[] = {
    #define ENTRY(objectType) [objectType] = @"" # objectType, 
        ETObjectTypeEntries
    #undef ENTRY
    };
    
    #define countof(array) (sizeof(array)/sizeof(array[0]))
    
    NSString *ETStringFromObjectType(ETObjectType type) {
        return ETObjectTypesAsStrings[type];
    }
    
    NSString *ETObjectTypeFromString(NSString *string) {
        NSString *match = nil;
        for(NSInteger idx = 0; !match && (idx < countof(ETObjectTypesAsStrings)); idx += 1) {
            if ([string isEqualToString:ETObjectTypesAsStrings[idx]]) {
                match = ETObjectTypesAsStrings[idx];
            }
        }
        return match;
    }
    

提交回复
热议问题