2011-08-22 147 views
0

任何人都可以解释为什么这代码工作完美:stringWithFormat错误访问错误

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

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

但这种代码导致错误访问错误?

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

回答

2

trunc返回double,不是int

double trunc(double x); 

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

在第二个,它应该是一个%f或在其前面有(int)

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

或者,更具体地说,%d期望一个32位参数,并且trunk返回一个64位参数。因此,%@试图将trunc()的返回值的后半部分视为一个id和** Boom **。 – bbum

+0

啊,我的错。我以为trunc返回一个整数。感谢澄清家伙。这个网站给了我更多的信息比我所有的目标C书结合起来。 – wayne

0

你试过从类型转换主干)返回(如....

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

这是一个在黑暗中拍摄,但我希望的NSString不知道该函数的返回类型TRUNC。