代码之家  ›  专栏  ›  技术社区  ›  sorin

cfStringCreateWithFormat需要哪种字符串作为参数?

  •  2
  • sorin  · 技术社区  · 16 年前

    下面的示例应适用于Unicode字符串,但不适用。

    
    CFStringRef aString =  CFSTR("one"); // in real life this is an Unicode string
    CFStringRef formatString = CFSTR("This is %s example"); // also tried %S but without success
    CFStringRef resultString = CFStringCreateWithFormat(NULL, NULL, formatString, aString);
    
    // Here I should have a valid sentence in resultString but the current result is like aString would contain garbage.
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   Chris Johnsen    16 年前

    使用 %@ 如果你想包括 CFStringRef 通过 CFStringCreateWithFormat .

    见 the Format Specifiers section of Strings Programming Guide for Core Foundation .

    • %@ 用于目标C对象,或 CFTypeRef 对象(对象) CFSTRIGRIEF 与兼容 法蒂珀夫 )
    • %s 用于8位无符号字符(即普通C字符串)的以空结尾的数组。
    • %S 用于16位Unicode字符的以空结尾的数组。

    cfStringRef对象与16位Unicode字符以空结尾的数组不同。

        2
  •  2
  •   Yuji    16 年前

    作为对另一个答案中评论的回答,我建议海报

    • 以可移植的方式生成一个utf8字符串 char*
    • 最后一分钟,把它转换成 CFString 使用 CFStringCreateWithCString 具有 kCFStringEncodingUTF8 作为编码。

    请不要使用 %s 在里面 CFStringCreateWithFormat . 请不要依赖“系统编码”,即西欧环境中的Macroman,而不要使用其他语言。系统编码的概念本质上是脑死亡的,特别是在东亚环境中(我来自东亚),即使是ASCII码范围内的字符(低于127!)被修改。如果你依赖于“系统编码”,地狱就会破灭。幸运的是,自从10.4以来,所有使用“系统编码”的方法现在都被弃用了, 除了 %s ….

    很抱歉,我为这个小话题写了这么多,但几年前有很多不错的应用程序因为这个“系统编码”而不能在日韩Mac上运行,这真是太可惜了。请参考 this detailed explanation 我几年前写的,如果你感兴趣的话。