2011-09-23 25 views
12

我有問題:我想避免[UIImage imageNamed:]。 所以我做:UIImage initWithContentsOfFile不起作用

UIImage *prodImg = [[UIImage alloc] initWithContentsOfFile:@"myimage.png"]; 
controller.productImg.image = prodImg; 
[prodImg release]; 

但現在的圖像不再顯示。

有誰知道如何得到這個工作?

+1

好吧,我得到了它的UIImage工作* prodImg = [[UIImage的頁頭] initWithContentsOfFile:[ NSBundle mainBundle] pathForResource:@「my image」ofType:@「png」]]; – Tanner

+0

建議:只需使用[UIImage imageNamed:@「myimage.png」],因爲它增加了緩存和設備擴展(「@ 2x」,「〜ipad」)邏輯 –

+2

With [UIImage imageNamed:@「myimage.png」]我得到了內存警告,看到這裏http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/ – Tanner

回答

25

上面的代碼是不工作,因爲正確的方式做到這一點是 -

NSString *thePath = [[NSBundle mainBundle] pathForResource:@"default" ofType:@"jpeg"]; 
UIImage *prodImg = [UIImage imageWithContentsOfFile:thePath]; 
controller.productImg.image = prodImg; 
[prodImg release]; 

;)