Skip to content

Instantly share code, notes, and snippets.

@priore
Last active February 28, 2016 02:54
Show Gist options
  • Save priore/6105fe881adf44f28431 to your computer and use it in GitHub Desktop.
Save priore/6105fe881adf44f28431 to your computer and use it in GitHub Desktop.
Convert property names in a text string with their value
// Convert property names in a text string with their value
object = user defined object
// your text below with the property names enclosed in square brackets
NSString *result = @"Your text here with macros eg. [name], [value], [description]";
NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:0 error:NULL];
NSArray *matches = [regEx matchesInString:result options:0 range:NSMakeRange(0, [text length])];
if (matches) {
for (NSTextCheckingResult *match in matches) {
NSString *macro = [[[text substringWithRange:match.range] stringByReplacingOccurrencesOfString:@"[" withString:@""] stringByReplacingOccurrencesOfString:@"]" withString:@""];
if ([object respondsToSelector:NSSelectorFromString(macro)])
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
result = [result stringByReplacingCharactersInRange:match.range withString:[NSString stringWithFormat:@"%@", [object performSelector:NSSelectorFromString(macro)]]];
#pragma clang diagnostic pop
else
result = [result stringByReplacingCharactersInRange:match.range withString:@""];
}
}
NSLog(@"%@", result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment