Best way to enum NSString

前端 未结 7 789
广开言路
广开言路 2021-02-02 13:23

Im digging for ways to enum objc object such as NSString, I remember there a new feature in a version of Xcode4+ which offering a new way to enum , but not clearly. Anyone know

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 13:32

    OK, I answered myself. Guess I make a mistake.

    This is the new feature I mentioned above:

    typedef enum Language : NSUInteger{
         ObjectiveC,
         Java, 
         Ruby, 
         Python, 
        Erlang 
    }Language;
    

    It's just a new syntax for enum in Xcode 4.4, but I'm so foolish to think we can exchange "NSUInteger" to "NSString".

    So here is the way I found that works:

    http://longweekendmobile.com/2010/12/01/not-so-nasty-enums-in-objective-c/

    // Place this in your .h file, outside the @interface block
    typedef enum {
        JPG,
        PNG,
        GIF,
        PVR
    } kImageType;
    #define kImageTypeArray @"JPEG", @"PNG", @"GIF", @"PowerVR", nil
    
    ...
    
    // Place this in the .m file, inside the @implementation block
    // A method to convert an enum to string
    -(NSString*) imageTypeEnumToString:(kImageType)enumVal
    {
        NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
        return [imageTypeArray objectAtIndex:enumVal];
    }
    
    // A method to retrieve the int value from the NSArray of NSStrings
    -(kImageType) imageTypeStringToEnum:(NSString*)strVal
    {
        NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
        NSUInteger n = [imageTypeArray indexOfObject:strVal];
        if(n < 1) n = JPG;
        return (kImageType) n;
    }
    

    FYI. The original author of the second example code created a category for enum handling. Just the thing for adding to your very own NSArray class definition.

    @interface NSArray (EnumExtensions)
    
    - (NSString*) stringWithEnum: (NSUInteger) enumVal;
    - (NSUInteger) enumFromString: (NSString*) strVal default: (NSUInteger) def;
    - (NSUInteger) enumFromString: (NSString*) strVal;
    
    @end
    
    @implementation NSArray (EnumExtensions)
    
    - (NSString*) stringWithEnum: (NSUInteger) enumVal
    {
        return [self objectAtIndex:enumVal];
    }
    
    - (NSUInteger) enumFromString: (NSString*) strVal default: (NSUInteger) def
    {
        NSUInteger n = [self indexOfObject:strVal];
        if(n == NSNotFound) n = def;
        return n;
    }
    
    - (NSUInteger) enumFromString: (NSString*) strVal
    {
        return [self enumFromString:strVal default:0];
    }
    
    @end
    

提交回复
热议问题