views:

120

answers:

2

My understanding of printf-like format strings is that you can prefix any conversion specifier with a minimum field width. This does not seem to work for Cocoa’s %@ specifier. Example:

NSLog(@"'%5@'", @"foo");
NSLog(@"'%5s'", [@"foo" UTF8String]);

Output:

… 'foo'
… '  foo'

Is this the intended behavior?

+1  A: 

%@ is only for objective-c object. Thus, the field width will be invalid, if the object is not NSString.

I didn't know that %5@ is formatted to be the same as %@.

Jesse Armand
Cocoa’s formatting function always calls `descriptionWithLocale:` (or `description`) on the object to get a string representation. This string representation could be padded to a given field width.
Nikolai Ruhe
A: 

The %@ format specifier just gets replaced by the object's description. It doesn't do any truncation or padding.

Graham Lee
Exactly. Don't you think that's wrong behavior? Or did you mean there's documentation which defines it to behave different to other format specifiers?
Nikolai Ruhe
@Nikolai: I make no value judgement over whether it's correct or not, I just said that's how it worked :).
Graham Lee