How do I enumerate on NSString?
How do I enumerate on NSString?
example of what I am trying to do:
enum eCat{
dog,
cat,
mouse,
bunny
};
@interface
@implementation开发者_如何学Python
....
enum eCat Cate;
NSString *yoda = @"mouse";
Cate = [yoda intValue];
NSLog(@"Hello: %d",Cate);
wanting the result to be
Hello: 2
thanks
You have to create a mapping (string → enumeration) yourself. One possibility would be something like this (disclaimer: only brain-compiled):
#define CAT_(a, b) a##b
#define CAT(a, b) CAT_(a, b)
#define E(en) [NSNumber numberWithInt:en], CAT(@, #en),
NSDictionary *mapping = [NSDictionary dictionaryWithObjectsAndKeys:
// ...
E(mouse)
E(bunny)
nil];
NSNumber *result = [mapping objectForKey:@"mouse"];
if (!result) {
// ... oops
} else {
enum eCat cate = [result intValue];
}
There's no direct support of such an enumeration in Objective-C.
Instead, create an array of the strings and look for an entry:
static NSArray* enumeration=nil;
if(!enumeration){
enumeration=[[NSArray arrayWithObjects:@"AAA",@"BBB",@"CCC",nil] retain];
}
then use it later:
NSInteger i=[enumeration indexOfObject:@"BBB"];
/* i is now 1 */
It's unrelated to your question, but please don't start a variable name with a capital letter, like your Cate
. That's against the convention of Objective-C.
精彩评论