May 27, 2008
NSArray and stringWithFormat:
The standard Cocoa method for a string with multiple replacements is [NSString stringWithFormat:]. To build a standard analogy string from the SATs:
hand : palm :: foot : sole
you would break out each of the replaceable elements into separate strings and replace them in the format string with the placeholder ‘%@’. (There are many other format specifiers–look up printf()–but ‘%@’ is very common in Cocoa since it specifies an Objective-C object, not just a simple number or C null-terminated string.)
NSString * format = @"%@ : %@ :: %@ : %@";
To create the desired string:
NSString * myString = [NSString stringWithFormat:format, @"hand", @"palm", @"foot", @"sole", nil];
If you want to create a different analogy string, just call stringWithFormat: again, using the same format string but different parameters following it.
The stringWithFormat: method takes a list of objects, and the nil parameter indicates the end of the list. If you want to manage the list of substitution parameters, though, you shouldn’t need that nil since NSArray knows how many elements it contains. Unfortunately, there isn’t a method like stringWithFormat: which takes an NSArray instead of a list of objects; there also doesn’t seem to be a simple way to convert the contents of an NSArray to a nil-terminated parameter list.
How then can you make this templating more dynamic at runtime by storing the list in an NSArray?
