加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 枚举NSString的最佳方式

发布时间:2020-12-15 01:54:07 所属栏目:百科 来源:网络整理
导读:我挖掘方法来枚举objc对象,如NSString,我记得在Xcode4版本中有一个新功能,提供了一种新的枚举方式,但不是很清楚。有人知道吗 解决方法 好的,我回答了自己。猜猜我犯了一个错误。 这是我上面提到的新功能 typedef enum Language : NSUInteger{ Objective
我挖掘方法来枚举objc对象,如NSString,我记得在Xcode4版本中有一个新功能,提供了一种新的枚举方式,但不是很清楚。有人知道吗

解决方法

好的,我回答了自己。猜猜我犯了一个错误。

这是我上面提到的新功能

typedef enum Language : NSUInteger{
     ObjectiveC,Java,Ruby,Python,Erlang 
}Language;

这只是Xcode 4.4中的枚举的新语法,但是我觉得我们可以将“NSUInteger”交换到“NSString”,我很愚蠢。

所以这里是我发现的方式:

http://longweekendmobile.com/2010/12/01/not-so-nasty-enums-in-objective-c/

// Place this in your .h file,outside the @interface block
typedef enum {
    JPG,PNG,GIF,PVR
} kImageType;
#define kImageTypeArray @"JPEG",@"PNG",@"GIF",@"PowerVR",nil

...

// Place this in the .m file,inside the @implementation block
// A method to convert an enum to string
-(NSString*) imageTypeEnumToString:(kImageType)enumVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    return [imageTypeArray objectAtIndex:enumVal];
}

// A method to retrieve the int value from the NSArray of NSStrings
-(kImageType) imageTypeStringToEnum:(NSString*)strVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    NSUInteger n = [imageTypeArray indexOfObject:strVal];
    if(n < 1) n = JPG;
    return (kImageType) n;
}

仅供参考。第二个示例代码的原始作者为枚举处理创建了一个类别。只是添加到你自己的NSArray类定义的东西。

@interface NSArray (EnumExtensions)

- (NSString*) stringWithEnum: (NSUInteger) enumVal;
- (NSUInteger) enumFromString: (NSString*) strVal default: (NSUInteger) def;
- (NSUInteger) enumFromString: (NSString*) strVal;

@end

@implementation NSArray (EnumExtensions)

- (NSString*) stringWithEnum: (NSUInteger) enumVal
{
    return [self objectAtIndex:enumVal];
}

- (NSUInteger) enumFromString: (NSString*) strVal default: (NSUInteger) def
{
    NSUInteger n = [self indexOfObject:strVal];
    if(n == NSNotFound) n = def;
    return n;
}

- (NSUInteger) enumFromString: (NSString*) strVal
{
    return [self enumFromString:strVal default:0];
}

@end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读