Spot the Difference, String Formatting

Check out these two snippets of code and see if you can spot the difference:

NSString *homeDir = NSHomeDirectory();
NSString *dataDir = [NSString stringWithFormat:@”%s/Documents/Data”, homeDir];

NSString *homeDir = NSHomeDirectory();
NSString *dataDir = [NSString stringWithFormat:@”%@/Documents/Data”, homeDir];

The first one uses the “C”-style “%s” format field for the string, which is incompatible with the NSString type string. It will subsequently scatter your files in seemingly random directories filled with jibberish in their names causing you untold hours of grief as you try to find them in what you believe to be the correct locations. The second one uses the correct “%@” format field. The moral of the story is that C and Objective-C are different in subtle but painfully significant ways…

Sometimes I suspect that my life is actually a series of cautionary tales for others.

Comments are closed.