Alguns NSString
métodos auxiliares para traduzir facilmente entre caixa de camelo e caixa de cobra. Observação: isso também poderia ser resolvido NSRegularExpression
, mas eu queria fornecer esta rota primeiro:
+ (NSString *)stringByReplacingSnakeCaseWithCamelCase:(NSString *)string
{
NSArray *components = [string componentsSeparatedByString:@"_"];
NSMutableString *camelCaseString = [NSMutableString string];
[components enumerateObjectsUsingBlock:^(NSString *component, NSUInteger idx, BOOL *stop) {
[camelCaseString appendString:(idx == 0 ? component : [component capitalizedString])];
if (idx > 0) {
[camelCaseString appendString:[component capitalizedString]];
} else {
[camelCaseString appendString:component];
}
}];
return [camelCaseString copy];
}
+ (NSString *)stringByReplacingCamelCaseWithSnakeCase:(NSString *)string
{
NSUInteger index = 1;
NSMutableString *snakeCaseString = [NSMutableString stringWithString:string];
NSUInteger length = snakeCaseString.length;
NSCharacterSet *characterSet = [NSCharacterSet uppercaseLetterCharacterSet];
while (index < length) {
if ([characterSet characterIsMember:[snakeCaseString characterAtIndex:index]]) {
[snakeCaseString insertString:@"_" atIndex:index];
index++;
}
index++;
}
return [snakeCaseString copy];
}