Skip to content

Instantly share code, notes, and snippets.

@michaelochs
Created December 13, 2016 15:37
Show Gist options
  • Save michaelochs/f106b5c42aafe6bed74ac5dab82281c4 to your computer and use it in GitHub Desktop.
Save michaelochs/f106b5c42aafe6bed74ac5dab82281c4 to your computer and use it in GitHub Desktop.
`NSFormattingContextDynamic` makes a formatter return string proxies that change based on where you but them inside a format string.
NSDate *date = [NSDate new];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"nl_NL"];
dateFormatter.dateStyle = NSDateFormatterFullStyle;
dateFormatter.formattingContext = NSFormattingContextDynamic; // this is the important setting
NSString *dateString = [dateFormatter stringFromDate:date];
NSString *s1 = [NSString stringWithFormat:@"Foo %@", dateString]; // "Foo dinsdag 13 december 2016"
NSString *s2 = [NSString stringWithFormat:@"%@ foo", dateString]; // "Dinsdag 13 december 2016 foo"
NSString *s3 = [NSString localizedStringWithFormat:@"Foo %@", dateString]; // "Foo dinsdag 13 december 2016"
NSString *s4 = [NSString localizedStringWithFormat:@"%@ foo", dateString]; // "Dinsdag 13 december 2016 foo"
NSLog(@">>>\n%@\n%@\n%@\n%@", s1, s2, s3, s4);
// also works inside NSLog:
NSLog(@"%@ - %@", dateString, dateString); // Dinsdag 13 december 2016 - dinsdag 13 december 2016
// but not in printf - which is kind of expected:
printf("%s - %s\n", dateString.UTF8String, dateString.UTF8String); // dinsdag 13 december 2016 - dinsdag 13 december 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment