I am doing something like this:
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *var1 = [standardUserDefaults objectForKey:@"obj1"];
NSString *var2 = [standardUserDefaults objectForKey:@"obj2"];
EmailUtil *email_obj = [[EmailUtil alloc] initWithSubject:@"Some subject" body:[[[@"This is var1: " stringByAppendingString: var1] stringByAppendingString:@" and var2: "] stringByAppendingString: var2]];
[email_obj send];
Where EmailUtil is just my own utility class which sends the email. This code works fine when the strings var1 and var2 are not nil; however, if they are nil the program will crash. What would be an elegant solution or good practice to follow to ensure the email is sent without a problem, regardless of what the values are?
Thanks!
Before your EmailUtil line, just add:
That should solve the crash at least.
Another and probably better way to do it would be to use NSString’s stringWithFormat.
Instead of:
Do:
I believe it will say (null) for the nil parameters (didn’t test this). This is probably cleaner than what I had, and your original code too.
Reference: String Format