0

Here's the deal: I have twenty five view controllers in my storyboard, each one has a UIImageView that displays a PNG with a large file size.

It turns out that a UIImageView inside a nib will load their image using [UIImageView initWithImage:[UIImage imageNamed:]] method (see the docs). The problem with using imageNamed: is that when each view controllers is loaded, the image in its UIImageView is placed in the cache, and my app quickly starts getting memory warnings and crashes.

The way out is to use [UIImageView initWithImage:[UIImage imageWithContentsOfFile:]], which loads the image but doesn't cache it. So what I'm trying to do is use in my NIB file a subclass of UIImageView that calls imageWithContentsOfFile. But I can't figure out how to grab the name of the image file that's set in the Attributes Inspector in Interface Builder.

UIImageViewNoCache.h

#import <UIKit/UIKit.h>

@interface UIImageViewNoCache : UIImageView
@end

UIImageViewNoCache.h

#import "UIImageViewNoCache.h"

@implementation UIImageViewNoCache

-(id)initWithImage:(UIImage *)image{
   self = [super init];
    if(self){
        self.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], theNameOfTheImageInTheNib];]
    }
}
@end

So, how can I get theNameOfTheImageInTheNib?

Eric
  • 16,003
  • 15
  • 87
  • 139
  • I don't think the image cache does what you think it does... Caching it, would REDUCE memory of the image across multiple uses – Justin Meiners Jun 27 '12 at 18:00
  • @JustinMeiners: Nope, it really increases memory size, read here: http://stackoverflow.com/questions/289360/problem-deallocing-memory-used-by-uiimageviews-with-fairly-large-image-in-an-ui – Eric Jun 27 '12 at 18:10
  • in that question I understand the problem was memory used by images is never being freed, not that the act of having the image cached made a copy or somehting – Justin Meiners Jun 27 '12 at 18:16
  • also you cannot get the name of the image, as the image, stores no information related to its name or filename, because they can be created in code etc, also if initWithImage is called wouldn't that image passed into the method already be in the cache? – Justin Meiners Jun 27 '12 at 18:26

1 Answers1

1

Have a look at this category I wrote: UIImage+SDSCache.

It swizzles imageNamed so not to use the cache. It could be useful to you as it is or as a sample of how to solve your specific issue.

sergio
  • 68,819
  • 11
  • 102
  • 123