2

My model comes from Core Data. My beans have images stored in the model as NSData.

To display my images, I need to do :

[UIImage imageWithData:bean.imageData] 

Is it OK if I do that everywhere ? I mean, from view #1 I display image by creating [UIImage imageWithData:], then I go on view #2 where I need to display the same image, but I only pass the bean between the 2 views, so I recreate the UIImage with [UIImage imageWithData].

I am wondering whether it takes too many CPU or memory if I do this... Do I need to manage a cache myself ? I think this might be quite common use case with CoreData so is there a common pattern to handle this ?

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

2

imageWithData will not cache your image (as per the docs, the only UIImage method to cache is imageNamed)

Here is an algorithm for caching images, though.

Community
  • 1
  • 1
HalR
  • 11,411
  • 5
  • 48
  • 80
2

In answer to your question, imageWithData is a bit slow, so, no you probably don't want to do this all over the place. You'd probably want to do some caching for maximum performance (or at least if you're likely to retrieve the same image repeated during a give session with the app). NSCache, like HalR suggested, is a great solution for that.

Furthermore, if the images are huge, you might not want to store them in CoreData at all, but rather store them in your Documents folder, and only store the filename path in CoreData. It's surprising how much slower it is to retrieve the image from your database and then use imageWithData is than it is to use imageWithContentsOfFile. Admittedly, if you're doing cacheing, you'll suffer this performance hit less often, but still, if you're retrieving lots of separate images, the difference is observable. With thumbnail images, though, it's less of an issue. Everyone draws this line in a different place, but for me, if the images are greater than 100kb each (or if I'm doing a lot of image retrieval), I'll use the Documents approach.

Rob
  • 415,655
  • 72
  • 787
  • 1,044