简体   繁体   中英

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 
....
enum eCat Cate;
NSString *yoda = @"mouse";
Cate = [yoda intValue];
NSLog(@"Hello: %d",Cate);

wanting the result to be

Hello: 2

thanks

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.

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM