I haven't found a better way than duplicating the enum in a string. However, I do it slightly differently, namely:
typedef enum {
kManipulateWindowTargetFrontWindow,
kManipulateWindowTargetNamedWindow,
kManipulateWindowTargetWindowNameContaining,
kManipulateWindowTargetDEFAULT = kManipulateWindowTargetFrontWindow,
} ManipulateWindowTargetType;
#define kManipulateWindowTargetTypeNamesArray @"FrontWindow", @"NamedWindow", @"WindowNameContaining", nil
then in the implementation:
static NSArray* kManipulateWindowTargetTypeArray = [[NSArray alloc] initWithObjects: kManipulateWindowTargetTypeNamesArray];
NSString* ManipulateWindowTargetTypeToString( ManipulateWindowTargetType mwtt )
{
return [kManipulateWindowTargetTypeArray objectAtIndex:mwtt];
}
ManipulateWindowTargetType ManipulateWindowTargetTypeFromString( NSString* s )
{
NSUInteger n = [kManipulateWindowTargetTypeArray indexOfObject:s];
check( n != NSNotFound );
if ( n == NSNotFound ) {
n = kManipulateWindowTargetDEFAULT;
}
return (ManipulateWindowTargetType) n;
}
The reason I use the #define is to avoid declaring the array in the header file, but it would be insane to separate the definition of the enum from the definition of the sequence of strings, so this is the best compromise I've found.
Since the code is boilerplate, you can actually make them a category on NSArray.
@interface NSArray (XMLExtensions)
- (NSString*) stringWithEnum: (NSUInteger) e;
- (NSUInteger) enumFromString: (NSString*) s default: (NSUInteger) def;
- (NSUInteger) enumFromString: (NSString*) s;
@end
@implementation NSArray (XMLExtensions)
- (NSString*) stringWithEnum: (NSUInteger) e;
{
return [self objectAtIndex:e];
}
- (NSUInteger) enumFromString: (NSString*) s default: (NSUInteger) def;
{
NSUInteger n = [self indexOfObject:s];
check( n != NSNotFound );
if ( n == NSNotFound ) {
n = def;
}
return n;
}
- (NSUInteger) enumFromString: (NSString*) s;
{
return [self enumFromString:s default:0];
}
@end
and then:
NSLog( @"s is %@", [kManipulateWindowTargetTypeArray stringWithEnum:kManipulateWindowTargetNamedWindow] );
ManipulateWindowTargetType mwtt = (ManipulateWindowTargetType)[kManipulateWindowTargetTypeArray enumFromString:@"WindowNameContaining" default:kManipulateWindowTargetDEFAULT];
NSLog( @"e is %d", mwtt );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…