Ugh, so on my way to making awesome Apps, I feel like I need to “upgrade” the basic libraries the iOS SDK comes with. Today was one of those instances.
I needed to upgrade their String class NSString
so that it could replace keys in it’s string with values from a NSDictionary
. The following is the very simple result using a Category.
@interface NSString (NSString_SFKeys)
- (NSString*) stringByReplacingOccurrencesOfKeysWithValues:(NSDictionary*)keyValuePairs;
@end
@implementation NSString (NSString_SFKeys)
- (NSString*) stringByReplacingOccurrencesOfKeysWithValues:(NSDictionary*)keyValuePairs
{
NSString *fStr = self;
if (keyValuePairs) {
for (NSString *key in [keyValuePairs allKeys]) {
NSString *value = [NSString stringWithFormat:@"%@",[keyValuePairs valueForKey:key]];
fStr = [fStr stringByReplacingOccurrencesOfString:key withString:value];
}
}
return fStr;
}
@end
And that’s that. Works great! Now I can do stuff like add story text like the following:
It was a dark and stormy night. {Player} looked out {pospronoun} window at a blackened sky.
And have it print:
It was a dark and stormy night. Jimmy looked out his window at a blackened sky.
Yay for smartness!