2011-09-23 57 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]; 

;)