-
-
Save vigorouscoding/4655844 to your computer and use it in GitHub Desktop.
A simple templating category for NSString. I made a couple of small changes to better suit my needs. (check out the diff to see what)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSString (Templating) | |
+(NSString*)stringWithTemplate:(NSString*)tpl | |
fromMap:(NSDictionary*)map; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "NSString+Templating.h" | |
@implementation NSString (Templating) | |
+(NSString*)stringWithTemplate:(NSString*)tpl | |
fromMap:(NSDictionary*)map | |
{ | |
NSString* retStr = nil; | |
NSMutableString* buffer = [NSMutableString new]; | |
NSScanner* scanner = [[NSScanner alloc] initWithString:tpl]; | |
// Otherwise spaces right after a bracket expression are skipped | |
[scanner setCharactersToBeSkipped:nil]; | |
NSString* tempString = nil; | |
while([scanner scanUpToString:@"$[" intoString:&tempString]) | |
{ | |
NSString* key = nil; | |
NSString* value = nil; | |
[buffer appendString:tempString]; | |
if([scanner isAtEnd]) | |
{ | |
break; | |
} | |
[scanner scanString:@"$[" intoString:nil]; | |
[scanner scanUpToString:@"]" intoString:&key]; | |
[scanner scanString:@"]" intoString:nil]; | |
if(key) | |
{ | |
value = [map objectForKey:key]; | |
} | |
if(value) | |
{ | |
// just 'value' does not work for NSNumber etc | |
[buffer appendString:[value description]]; | |
} | |
else | |
{ | |
[buffer appendFormat:@"$[%@]", key]; | |
} | |
} | |
retStr = [NSString stringWithString:buffer]; | |
[buffer release]; | |
[scanner release]; | |
return retStr; | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)test | |
{ | |
NSString* testTemplate = @"Hello $[name], welcome to $[city]."; | |
NSString* testString = [NSString stringWithTemplate:testTemplate fromMap:@{@"name" : @"Popcorny", @"city", @"Taipei"}]; | |
NSLog(@"%@", testString); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment