2

Was reading the response by Shaggy Frog to this post and was intrigued by the following line of code:

NSLog(@"%@", [NSString stringWithFormat:@"%@:%*s%5.2f", key, padding, " ", [object floatValue]]);

I know string formatting is an age old art but I'm kinda doing the end around into Cocoa/Obj-C programming and skipped a few grades along the way. Where is a good (best) place to learn all the string formatting tricks allowed in NSString's stringWithFormat? I'm familiar with Apple's String Format Specifiers page but from what I can tell it doesn't shed light on whatever is happening with %*s or the %5.2f (not to mention the 3 apparent placeholders followed by 4 arguments) above?!?

Community
  • 1
  • 1
Meltemi
  • 37,979
  • 50
  • 195
  • 293
  • 1
    I can see why `NSLog(@"%@", [NSString stringWithFormat: @"...", ...]);` was used in that answer (to parallel the question), but `NSLog(@"...", ...);` should work identically and it reads more easily. – Isaac Apr 23 '10 at 23:06
  • `%*s` is a printf feature from C99 – user102008 Jul 30 '11 at 02:19

1 Answers1

2

The documentation of -stringWithFormat leads you to String Format Specifier which in turn sends you to the IEEE printf specification. That's about as much information as you'll ever want.

The only notable exception:

%@

Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.

  • nil gets converted to (null), that's the reason why NSLog(@"%@", someObject) is safer than NSLog("someObject). The later might crash when someObject is nil:

You might also be interested in the wikipedia page about string formatting.

J...
  • 30,968
  • 6
  • 66
  • 143
Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
  • ya. that i know.. what i don't know is a good source describing all the printf string argument manipulation tricks/techniques. – Meltemi Apr 23 '10 at 19:52
  • 4
    `man printf` is a good place to start (the Cocoa methods follow the same practices, which the additions listed above), although the wiki page linked above is basically just a fancy form of the `printf` man page. For example, `%*s` uses two specifies, `*` and `s`; both are described on the man page (`*` in the "width" section, and `s` in the type section). – mipadi Apr 23 '10 at 20:01