Convert property names in a text string with their value

priore Oct 10th, 2014 (edited) 604 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Convert property names in a text string with their value
  2. object = user defined object
  4.     // your text below with the property names enclosed in square brackets
  5.     NSString *result = @"Your text here with macros eg. [name], [value], [description]";
  6.     NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:0 error:NULL];
  7.     NSArray *matches = [regEx matchesInString:result options:0 range:NSMakeRange(0, [text length])];
  8.     if (matches) {
  9.         for (NSTextCheckingResult *match in matches) {
  10.             NSString *macro = [[[text substringWithRange:match.range] stringByReplacingOccurrencesOfString:@"[" withString:@""] stringByReplacingOccurrencesOfString:@"]" withString:@""];
  11.             if ([object respondsToSelector:NSSelectorFromString(macro)])
  12. #pragma clang diagnostic push
  13. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  14.                 result = [result stringByReplacingCharactersInRange:match.range withString:[NSString stringWithFormat:@"%@", [object performSelector:NSSelectorFromString(macro)]]];
  15. #pragma clang diagnostic pop
  16.             else
  17.                 result = [result stringByReplacingCharactersInRange:match.range withString:@""];
  18.         }
  19.     }
  21. NSLog(@"%@", result);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand