简体   繁体   English

如何枚举 NSString?

[英]How do I enumerate on NSString?

How do I enumerate on NSString?如何枚举 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. 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 .这与您的问题无关,但请不要以大写字母开头变量名,例如您的Cate That's against the convention of Objective-C.这违反了 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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