代码之家  ›  专栏  ›  技术社区  ›  Evan DiBiase

为什么NSString和NSLog处理%C和%lc(以及%S和%ls)的方式不同?

  •  5
  • Evan DiBiase  · 技术社区  · 16 年前

    苹果的 String Format Specifiers

    IEEE printf specification

    但是,虽然 printf %C %lc %S 作为等效物 %ls C S NSLog +[NSString stringWithFormat:] .

    例如,考虑以下代码:

    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        unichar str[3];
        str[0] = 63743;
        str[1] = 33;
        str[2] = (unichar)NULL;
    
        NSLog(@"NSLog");
        NSLog(@"%%S:  %S", str);
        NSLog(@"%%ls: %ls", str);
    
        NSLog(@"%%C:  %C", str[0]);
        NSLog(@"%%lc: %lc", str[0]);
    
        NSLog(@"\n");
        NSLog(@"+[NSString stringWithFormat:]");
    
        NSLog(@"%%S:  %@", [NSString stringWithFormat:@"%S", str]);
        NSLog(@"%%ls: %@", [NSString stringWithFormat:@"%ls", str]);
    
        NSLog(@"%%C:  %@", [NSString stringWithFormat:@"%C", str[0]]);
        NSLog(@"%%lc: %@", [NSString stringWithFormat:@"%lc", str[0]]);
    
        [pool drain];
        return 0;
    }
    

    输出函数

    2009-03-20 17:00:13.363 UnicharFormatSpecifierTest[48127:10b] NSLog
    2009-03-20 17:00:13.365 UnicharFormatSpecifierTest[48127:10b] %S:  !
    2009-03-20 17:00:13.366 UnicharFormatSpecifierTest[48127:10b] %ls: ˇ¯!
    2009-03-20 17:00:13.366 UnicharFormatSpecifierTest[48127:10b] %C:  
    2009-03-20 17:00:13.367 UnicharFormatSpecifierTest[48127:10b] %lc: 
    2009-03-20 17:00:13.367 UnicharFormatSpecifierTest[48127:10b] 
    2009-03-20 17:00:13.368 UnicharFormatSpecifierTest[48127:10b] +[NSString stringWithFormat:]
    2009-03-20 17:00:13.368 UnicharFormatSpecifierTest[48127:10b] %S:  !
    2009-03-20 17:00:13.369 UnicharFormatSpecifierTest[48127:10b] %ls: ˇ¯!
    2009-03-20 17:00:13.369 UnicharFormatSpecifierTest[48127:10b] %C:  
    2009-03-20 17:00:13.370 UnicharFormatSpecifierTest[48127:10b] %lc: 
    

    1 回复  |  直到 16 年前
        1
  •  6
  •   Peter Hosey    16 年前

    在Mac OS X上, <machine/_types.h> 定义 wchar_t int

    正如你所注意到的 printf %S %ls ,它需要一个指针指向一些 wchar_t *

    然而,您链接到的Cocoa文档(及其CF等效文件)确实定义了 S

    • S :以空结尾的数组 Unicode字符

    %C .

    S C 输出函数 它的表亲们会解读它们。CF和Cocoa将字符视为UTF-16,而 输出函数

    在使用核心服务时,CF/Concoa解释更有用,因为一些API(如文件管理器)会将文本作为数组传递给您 UniChar S 打印字符串。