Skip to content

Instantly share code, notes, and snippets.

@irace
Created August 14, 2012 13:51
Show Gist options
  • Save irace/3349415 to your computer and use it in GitHub Desktop.
Save irace/3349415 to your computer and use it in GitHub Desktop.
Micro-templating for iOS
// https://github.com/jasonmoo/t.js, http://news.ycombinator.com/item?id=4378578
static inline NSString *F(NSString *string, id object) {
NSMutableString *result = [[string mutableCopy] autorelease];
void (^replace)(NSMutableString *, NSString *, id) =
^ (NSMutableString *string, NSString *key, id value) {
NSString *stringValue = [value isKindOfClass:[NSNumber class]]
? [NSString stringWithFormat:@"%@", (NSNumber *)value] : value;
[string replaceOccurrencesOfString:key withString:stringValue options:NSCaseInsensitiveSearch
range:NSMakeRange(0, [string length])];
};
if ([object isKindOfClass:[NSArray class]]) {
NSArray *array = (NSArray *)object;
for (int key = 0; key < array.count; key++)
replace(result, [NSString stringWithFormat:@"{%d}", key], [array objectAtIndex:key]);
} else if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = (NSDictionary *)object;
for (NSString *key in [dictionary allKeys])
replace(result, [NSString stringWithFormat:@"{%@}", key], [dictionary objectForKey:key]);
}
return result;
}
F(@"My name is {0} {1}", @[@"Bryan", @"Irace"]);
F(@"I am {age} years old", @{ @"age" : @26 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment