12

I have question: I want to avoid [UIImage imageNamed:]. So i did:

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

But now the image is not shown anymore.

Does anyone know how to get that to work?

EmptyStack
  • 51,274
  • 23
  • 147
  • 178
Tanner
  • 133
  • 1
  • 2
  • 5
  • 1
    Ok, I got it working with UIImage *prodImg = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"my image" ofType:@"png"]]; – Tanner Sep 23 '11 at 07:09
  • suggestion: just use `[UIImage imageNamed:@"myimage.png"]` because it adds caching and device extension ("@2x", "~ipad") logic – Martin Ullrich Sep 23 '11 at 07:26
  • 2
    With [UIImage imageNamed:@"myimage.png"] I get memory warnings, see here http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/ – Tanner Sep 23 '11 at 08:21
  • that might be because you hang on to the UIImages for a long time.. if you just assign it to a UIImageView and don't retain it you sould be fine. AND using jpg-Files on iOS is dangerous for memory consumption (use png-format and `pngcrush -iphone` command-line tool). – Martin Ullrich Sep 23 '11 at 08:44
  • +1 for imageNamed is evil. Saw exactly the same effect. Proposed solution eliminated out of memory warning and eliminated crashes. – Rich Apodaca Sep 25 '12 at 18:41

1 Answers1

26

The above code is not working because correct way to do it is-

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

;)

Karen Hovhannisyan
  • 1,140
  • 2
  • 21
  • 31
Devarshi
  • 16,440
  • 13
  • 72
  • 125