【问题标题】:Convert NSString to string将 NSString 转换为字符串
【发布时间】:2010-05-28 04:58:07
【问题描述】:
NSDate *now = [NSDate date];                                 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];                    
[formatter setDateFormat:@"yyyy"];                     

NSString *stringFromDate = [formatter stringFromDate:now]; 
CGContextShowTextAtPoint(context, 50, 50, stringFromDate, 5);

我没有得到确切的日期?编译时也收到警告
警告:从不兼容的指针类型传递“CGContextShowTextAtPoint”的参数 4

【问题讨论】:

    标签: objective-c iphone


    【解决方案1】:

    函数的原型是:

    void CGContextShowTextAtPoint (
       CGContextRef c,
       CGFloat x,
       CGFloat y,
       const char *string,
       size_t length
    );
    

    但在第 4 个参数中,您传递的是 *NSString **(而不是函数原型要求的 *const char **)。

    您可以使用 NSString 的 cStringUsingEncoding 方法将 NSString 转换为 C 字符串,例如:

    CGContextShowTextAtPoint(context, 50, 50, [stringFromDate cStringUsingEncoding:NSASCIIStringEncoding]);
    

    【讨论】:

    • 在这种情况下没问题,因为日期格式是 yyyy,但一般来说,如果没有测试 NULL 返回值,你永远不应该使用[someString cStringUsingEncoding:NSASCIIStringEncoding]。例如,如果日期格式设置为长日期格式,并且代码在法语区域设置的 iPhone 上运行并且月份是八月(或在法国说的 août),则将传递一个空指针作为第四个参数。最好的情况是不显示文本,最坏的情况是段错误。
    • 使用UTF8String 的充分理由。 :)
    • 好点,但使用 [NSString drawAtPoint:withFont:] ref stackoverflow.com/questions/1237565/…stackoverflow.com/questions/2087418/… 看起来更好
    【解决方案2】:

    stringFromDate 的值是多少?你期待什么?

    在编译时也会收到警告 警告:传递参数 4 'CGContextShowTextAtPoint' 来自 指针类型不兼容

    如果您查看CGContextShowTextAtPoint 的文档,您会发现第四个参数必须是char*,而不是NSString*.

    你有:

    GContextShowTextAtPoint(context, 50, 50, stringFromDate, 5);
    

    你想要:

    GContextShowTextAtPoint(context, 50, 50, [stringFromDate UTF8String], 5);
    

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 2015-11-30
      • 2013-12-12
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多