5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-Cでenumに対応した文字列を定義し、キャストする

Last updated at Posted at 2017-02-14

enumと文字列を、enum -> NSString、 NSString -> enumと相互にキャストする汎用な方法を調べたときのメモです。

1. NSArrayのExtensionとしてキャストするメソッドを用意します。

NSArray+EnumExtensions.h
//
//  NSArray+EnumExtensions.h
//

#import <Foundation/Foundation.h>

@interface NSArray (EnumExtensions)

/**
 * enum to string
 * @param value enum value
 * @return NSString string value
 */
- (NSString *)stringFromEnum:(NSInteger)value;

/**
 * string to enum
 * @param value string value
 * @return NSInteger enum value
 */
- (NSInteger)enumFromString:(NSString *)value;

/**
 * string to enum
 * @param value string value
 * @param def default enum value
 * @return NSInteger enum value
 */
- (NSInteger)enumFromString:(NSString *)value def:(NSInteger)def;


@end

NSArray+EnumExtensions.m
//
//  NSArray+EnumExtensions.m
//

#import "NSArray+EnumExtensions.h"
#import <Foundation/Foundation.h>

@implementation NSArray (EnumExtensions)

- (NSString *)stringFromEnum:(NSInteger)value {
    return [self objectAtIndex:value];
}

- (NSInteger)enumFromString:(NSString *)value {
    return [self enumFromString:value def:0];
}

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

@end

2. enumと定義と一緒に文字列の定義をマクロで記述します

typedef NS_ENUM(NSInteger, MyType) {
    kMyTypeFoo,
    kMyTypeBar,
    kMyTypeBaz
};

// enumと定義と一緒に文字列定義をマクロで記述
#define MyTypeStrings @[@"Foo", @"Bar", @"Baz"]

使い方

// enum -> NSString
NSString *stringValue = [MyTypeStrings stringFromEnum:kMyTypeBar];
NSLog(@"%@", stringValue);
// -> Bar
    
// NSString -> enum
MyType enumValue = [MyTypeStrings enumFromString:stringValue];
NSLog(@"%d", (int)enumValue);
// -> 1
    
// NSString(with default) -> enum
MyType enumValue2 = [MyTypeStrings enumFromString:@"undefined" def:kMyTypeFoo];
NSLog(@"%d", (int)enumValue2);
// -> 0

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?