I want to do the following:
["Hello <firstname> <middlename> <lastname>". replaceTokensWithStrings:
@"firstname", someFirstName,
@"middlename", middleNameMightBeNilObject,
@"lastname", lastNameObject];
It looks like this is not possible because of the “nil as a terminator problem”.
However NSLog also takes multiple arguments and can handle nil as parameters too:
NSString *nilValue = nil;
NSLog(@"Value of nilValue=%@", nilValue);
output
Value of nilValue=(null)
So how can I achieve this in my replaceTokensWithStrings:... method?
Update: The signature of my method:
-(NSString *)replaceTokensWithStrings:(NSString *)input, ... NS_SOMETHING_SPECIAL_HERE{
NSLogcounts the number of format specifiers (%@,%i, etc.) in its format string (the first argument, the literal string) in order to know how many arguments it should pull off the call stack. This is why it can handlenilarguments — it is using the count to terminate its processing (and, incidentally, why it will often crash if you give it too few arguments).Since you have a format-type string, you can do the same thing — just whip up a helper method that counts the number of
<something>elements in the string on whichreplaceTokensWithStrings:has been called, and use the results to limit your processing of theva_list.The
NS_SOMETHING_SPECIALin your method declaration would beNS_REQUIRES_NIL_TERMINATIONfor the case where you’re usingnilas a sentinel. You don’t need anything special if you’re getting the count of arguments from somewhere.