I want to create an enum-like set of strings in a way that will also provide me the ability开发者_JS百科 to order them by their ordinal value and NOT by alphabetic value. for example:
"Extremely Low" = 0
"Very Low" = 1
"Low" = 2
"Medium = 3
"High" = 4
and so on.
I know that in Java and C# for example, enum types can have a value besides their ordinal value.
Is there any way to achieve the same goal in Objective-C?
Thanks!
I don't know a direct way to do that. However, you can define an Obj-C class like this:
@interface EnumLike : NSObject
{
NSString* title;
NSInteger value;
}
@property (nonatomic, readonly) NSString* title;
@property (nonatomic, readonly) NSInteger value;
// Something like enum
+ (id)extremelyLow;
+ (id)veryLow;
...
+ (id)high;
};
Except working with the switch this can do the job. I use similar types from time to time to declare some "enums" for the user since a list of such instances can be binded to an NSArrayController and used in the UI.
Just keep the strings for I/O and use an enum for all your computations. For example, define your enum:
typedef enum { ExtremelyLow, VeryLow, ... High } Rating;
You can use this enum in switch
statements etc. Now you can use an NSArray
or just a simple C-array to map from enum literals to strings:
NSString *RatingToString[] = { @"Extremely Low", @"Very Low", ..., @"High" };
Rating myRating;
NSString *strMyRating = RatingToString[myRating];
Going from the string version to the enum is more involved, you can use the same RatingToString
array and do appropriate comparisons (case-insensitive maybe, fuzzy etc.). You could also use an NSDictionary
:
NSDictionary StringToRating = [NSDictionary dictionaryWithObjectsAndKeys: RatingToString[ExtremelyLow], [NSNumber numberWithInt:ExtremelyLow, ..., nil];
Now a lookup will do an exact match on your string and return a Rating
wrapped as an NSNumber
.
You can use a class like Gobra suggested or an array of c structs:
typedef struct {
int type;
NSString *desc;
} NXENumToNSString;
NXENumToNSString kNXGMWidgetTypes[] = {
{1, @""},
{2, @"imageGallery"},
{3, @"dotImageGallery"},
{4, @"video"},
{5, @"webView"},
{6, @"image"}
};
NSInteger
intToStringForArray(NXENumToNSString *buffer, size_t length, NSString *str)
{
int result = NSIntegerMin;
NXENumToNSString *scan, *stop;
scan = buffer;
stop = scan + length;
while (scan < stop) {
if ([scan->desc isEqualToString:str]) {
result = scan->type;
break;
}
scan++;
}
return result;
}
then you can do something like this:
size_t l = sizeof(kNXGMWidgetTypes) / sizeof(NXENumToNSString);
NSInteger result = intToStringForArray(kNXGMWidgetTypes, l, str);
精彩评论