【问题标题】:stringWithFormat Bad Access errorstringWithFormat 错误访问错误
【发布时间】:2011-08-22 16:19:43
【问题描述】:

谁能解释一下为什么这段代码可以完美运行:

int thumbnailPrefix = trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]);

newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",thumbnailPrefix,@"png"];

但是这段代码会导致 Bad Access 错误?

newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]),@"png"];

【问题讨论】:

    标签: objective-c ios exc-bad-access stringwithformat


    【解决方案1】:

    trunc 返回 double,而不是 int

    double trunc(double x);
    

    因此,在第一个代码块中,您将其转换为int,并正确使用%d 格式说明符。

    第二个应该是%f,或者前面有(int)

    newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",(int)trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]),@"png"];
    

    【讨论】:

    • 或者,更具体地说,%d 需要一个 32 位参数,而 trunk 返回一个 64 位参数。因此,%@ 试图将 trunc() 的返回值的后半部分视为 id 和 Boom
    • 啊,我的错。我以为 trunc 返回一个整数。感谢您澄清。这个网站给我的信息比我所有的目标 C 书籍加起来还要多。
    【解决方案2】:

    您是否尝试过将 trunk() 的返回进行类型转换,例如......

    newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",(int)trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]),@"png"];
    

    这是在黑暗中的一个镜头,但我希望 NSString 不知道函数 trunc 的返回类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多