Skip to content

Instantly share code, notes, and snippets.

@gustafnilklint
Created October 10, 2014 11:39
Show Gist options
  • Save gustafnilklint/58c80fa27c0019a382f3 to your computer and use it in GitHub Desktop.
Save gustafnilklint/58c80fa27c0019a382f3 to your computer and use it in GitHub Desktop.
String with format, avoiding "(null)" "<null>" and extra spaces, drop this method in your NSString category
// Returns a string with the given format, any nil-values will be eliminated and extra white-space is trimmed away for you =)
+ (instancetype)safeStringWithFormat:(NSString *)format, ...
{
va_list ap;
va_start(ap, format);
NSString *intermediateString = [[NSString alloc] initWithFormat:format arguments:ap];
va_end(ap);
NSString *resultString = [intermediateString stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
resultString = [resultString stringByReplacingOccurrencesOfString:@"<null>" withString:@""];
NSString *squashed = [resultString stringByReplacingOccurrencesOfString:@"[ ]+"
withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, resultString.length)];
return [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment