When NSString Doesn’t Create A String With A String

If one goes to the NSString documentation, one quickly realizes that there is a very nice convenience method,

+ (id)stringWithString:(NSString *)aString


    The string from which to copy characters. This value must not be nil.

Raises an NSInvalidArgumentException if aString is nil.

Return Value
A string created by copying the characters from aString.

One would be forgiven for not noticing that little note that is supposed to catch your attention by having the title, Important. And it is important. Because, let’s say that you are trying to tell your iOS user how much an app feature upgrade cost,

NSString *titleString1 = [NSString stringWithString:@"Upgrade Flush'em for "];
NSString *titleString2 = [NSString stringWithString:[PFIAPManager sharedManager].upgradePrice];
NSString *titleString3 = [titleString1 stringByAppendingString:titleString2];
NSString *titleMessage = [titleString3 stringByAppendingString:@"?"];

Now let’s say that your intrepid customer doesn’t have a network connection. Yes, you can go through the mental exercise of asking why in the world a user would try to upgrade a mobile app without a network connection, but trust me, it will happen. And you as a responsible programmer must catch that error and handle it well for the customer. And how would you do that?

NSString *titleString2 = nil;
NSString *upgradePriceStr = [PFIAPManager sharedManager].upgradePrice;
if (upgradePriceStr)
titleString2 = [NSString stringWithString:upgradePriceStr];