I have a long string I want to retrieve from a URL and store at app launch. Later, I want to insert individual values into that string.
I’d like to do something like this:
NSString *numberLine = @"1 %@ 3 %@ 5 %@";
//... (later) ...
NSString *final = [NSString stringWithFormat:numberLine, @"two", @"four", @"six"];
NSLog(@"%@", final); //Should output "1 two 3 four 5 six"
I want the @"two" to be inserted into the placeholder %@ that was earlier saved into numberLine.
Is there a good way to accomplish something like this?
So far my only thought is to do something like:
NSString *script = @"width = PLACEHOLDERpx";
script = [script stringByReplacingOccurrencesOfString:@"PLACEHOLDER" withString:@"12"];
What you are describing is a template. You want to leave placeholders in a string that will be filled out with data. While you could use %@ and %d through a string that gets difficult as the string grows more complex. You may want to use a template library like Mustache for Objective-C. This will let you write expressions like this:
All you have to do is pass in an
NSDictionarywith keys that correspond to the data you want to render. So for the example above you might do the following:This will produce a
resultstringHello World.