エンジニアリングにはほど遠い

iPhoneアプリとかサイトとかをつくっていくブログです。

Objective-C キャメル・スネークケース変換

超小ネタです。toSnakeCaseは最初の文字が大文字のものにはちゃんと対応していません。

NSString+CamelSnake.m

#import "NSString+CamelSnake.h"

@implementation NSString (CamelSnake)

- (NSString *)toCamelCase
{
    NSMutableString *result = [NSMutableString new];
    [[self componentsSeparatedByString:@"_"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [result appendString:idx == 0 ? obj : [obj capitalizedString]];
    }];
    return (NSString *)result;
}

- (NSString *)toSnakeCase
{
    NSMutableString *result = [self mutableCopy];
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: @"[A-Z]"
                                                                           options:0
                                                                             error:nil];
    [regex replaceMatchesInString:result
                          options:0
                            range:NSMakeRange(0, [result length])
                     withTemplate:@"_$0"];
    return [result lowercaseString];
}

@end