DCMaxxx
DCMaxxx

Reputation: 2574

Good practice loading UIImage

I have a few icons in my app that I reuse in multiple views (for example a favorite icon).

In order to save memory, I was wondering if using a class with class methods which loads static images would be a good idea ?

For example :

+ (UIImage *)favoriteIcon {
    static UIImage * icon;
    if (!icon)
        icon = [UIImage imageNamed:@"favorite.png"];
    return icon;
}

Or should I just use + (UIImage *) imageNamed:(NSString *)name every time I need ?

Thank you for your advices.

Upvotes: 2

Views: 254

Answers (1)

benzado
benzado

Reputation: 84308

[UIImage imageNamed:] is already doing something like this under the hood. In fact, it's smarter, because it is also doing things like dumping the images when memory is low and they aren't needed right away, while your favoriteIcon method keeps them loaded forever.

In general, it's better to avoid doing optimizations like this until you've built your app and then profiled it to see how/where it needs improvement. Otherwise you are wasting time or maybe even making things worse. I recommend you learn how to use Instruments to profile your app, it's kind of complicated but a lot of fun once you get the hang of it.

Upvotes: 6

Related Questions