本文介绍了诸如 `%15@` 之类的格式说明符在 NSLog 中有效,但在 NSString stringWithFormat 中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试将宽度说明符与 %@ 一起使用时,我发现了一些奇怪的东西.它们在 NSLog 中工作正常,但在 NSString stringWithFormat: 中无效.

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

示例:

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

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

你得到了预期的输出:

|             foo | 1               |

但是将 NSLog 替换为 stringWithFormat::

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

test的值不正确:

| foo | 1 |

如果我将其更改为使用 %scStringUsingEncoding: 那么它就可以工作了:

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

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

结果与NSLog相同.

真正奇怪的是,NSLog 基本上只是对 NSString stringWithFormat: 的包装.

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

为什么会有不同的结果?为什么 stringWithFormat 中的 %@ 没有格式说明符,但它们与 NSLog 一起使用?

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

作为旁注,Swift String init(format:) 初始化器与 %@ 和宽度说明符存在相同的问题.

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

推荐答案

神秘的是为什么 %15@永远工作.不应该.

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

格式说明符来自sprintf,它没有%@(它只是Objective-C 的一个特殊扩展).就 stringWithFormat 而言,%15s 一直 是这样说的;我可以引用 Stack Overflow 示例,例如 NSString stringwithformat: Padding 2 strings with未知长度.

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.

我猜它只是有效",因为它现在在底层使用 os_log ;不幸的是,os_log 语法几乎完全没有记录.

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

这篇关于诸如 `%15@` 之类的格式说明符在 NSLog 中有效,但在 NSString stringWithFormat 中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 06:47