NSLog(@“% - 20s%-32s”,[theCard.name UTF8String])%-32s是什么意思?

时间:2013-04-03 06:12:43

标签: objective-c

我正在研究Objective-C,我知道NSLog可以打印出来,但我迷失了这个%-20s%-32s。

这是什么-20s和-32s在这里做什么

  -(void) list
    {
    NSLog (@"======== Contents of: %@ =========", bookName);
    for ( AddressCard *theCard in book )
    NSLog (@"%-20s %-32s", [theCard.name UTF8String],
    [theCard.email UTF8String]);
    Array Objects 339
    NSLog (@"==================================================");
    }
    @

====================================
|                                  |
| Tony Iannino                     |
| tony.iannino@techfitness.com     |
|                                  |
|                                  |
|                                  |
| O O                              |
====================================

2 个答案:

答案 0 :(得分:3)

它们是printf格式说明符,用于打印20和32个字符的字符串,右边是空格。

% start of the specifier
- align the field to left instead of right
32 width of field
s type of field is string

完整文档:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

答案 1 :(得分:1)

NSLog()了解带有某些扩展名的printf()格式字符串,因此您可以在documentation of printf()中查找以下内容:

  

每个转换规范由'%'字符引入[XSI]   或字符序列“%n $”[...]

     
      
  • 零个或多个标志[...]
  •   
  • 可选的最小字段宽度[...]
  •   
  • 可选精度[...]
  •   
  • 可选的长度修饰符[...]
  •   
  • 转换说明符字符,指示要应用的转换类型。
  •   
     

[...]

     

旗帜字符及其含义为:

     

[...]

     

- :转换结果应在左对齐   场。如果此标志不是,则转换是右对齐的   指定。 [...]

     

转换说明符及其含义为:

     

[...]

     

s:The   参数应该是指向char数组的指针。阵列的字节数   应写入(但不包括)任何终止空字节。   如果指定了精度,则不应超过那么多字节   书面。如果未指定精度或大于该大小   对于数组,应用程序应确保数组包含一个   空字节。

     

[...]

所以,这个转换的作用是打印一个const char数组,分别打印20和32个字符,用右边的空格填充它,以便让对象生效。