2011-08-22 144 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。