I recently needed to convert a Core Data attribute name, which uses
camel case, so they could be displayed as capitalized words for use in a label. This would give me the ability to label rows in a Core Data backed detail editing view without having to manually specify the labels.
I decided not to use this option because I would have lost the ability to localize my application since my attribute names are always and only in English. But, I thought I'd throw this category up for anyone who might need it. This functionality could come in useful, for example, when building a Core Data developer utility.
NSString-CamelCase.h#import <Foundation/Foundation.h>
@interface NSString(CamelCase)
-(NSString *)stringByConvertingCamelCaseToCapitalizedWords;
@end
NSString-CamelCase.h#import "NSString-CamelCase.h"
@implementation NSString(CamelCase)
-(NSString *)stringByConvertingCamelCaseToCapitalizedWords {
NSMutableString *ret = [NSMutableString string];
for (NSUInteger i = 0; i < [self length]; i++) {
unichar oneChar = [self characterAtIndex:i];
if ([[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:oneChar])
[ret appendFormat:@" %C", oneChar];
else
[ret appendFormat:@"%C", oneChar];
}
return [[ret capitalizedString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
@end
No comments:
Post a Comment