A format specifier such as `%15@` works in NSLog but not with NSString stringWithFormat

♀尐吖头ヾ 提交于 2019-12-06 05:24:57

问题


I found something strange when trying to use width specifiers with %@. They work fine in NSLog but not with NSString stringWithFormat:.

Example:

NSString *rightAligned = @"foo";
NSString *leftAligned = @"1";

NSLog(@"| %15@ | %-15@ |", rightAligned, leftAligned);

And you get the expected output of:

|             foo | 1               |

But replace the NSLog with stringWithFormat::

NSString *test = [NSString stringWithFormat:@"| %15@ | %-15@ |", rightAligned, leftAligned];

And the value of test is incorrectly:

| foo | 1 |

If I change this to use %s and cStringUsingEncoding: then it works:

NSString *test2 = [NSString stringWithFormat:@"| %15s | %-15s |", [rightAligned cStringUsingEncoding:NSUTF8StringEncoding], [leftAligned cStringUsingEncoding:NSUTF8StringEncoding]];

The result is the same as with NSLog.

What makes this really strange is that NSLog is basically just a wrapper around NSString stringWithFormat:.

So why the different results? Why aren't format specifiers honored for %@ in stringWithFormat but they are with NSLog?

As a side note, the Swift String init(format:) initializer has the same problem with %@ and width specifiers.


回答1:


The mystery is why %15@ would ever work. It should not.

Format specifiers come from sprintf which has no %@ (it is just a special extension for Objective-C). As far as stringWithFormat goes, %15s has always been the way to say this; I can cite Stack Overflow examples such as NSString stringwithformat: Padding 2 strings with unknown length.

I'm guessing it only "works" because it now uses os_log under the hood; unfortunately, the os_log syntax is almost completely undocumented.



来源:https://stackoverflow.com/questions/55942555/a-format-specifier-such-as-15-works-in-nslog-but-not-with-nsstring-stringwit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!