Malloc
Malloc

Reputation: 16276

imageNamed and imageWithContentsOfFile cache image: Anyway to clear cache?

I am loading a default image when no image is found from the remote server:

   detailImageView.image = [UIImage imageNamed:@"noimageavailable.jpg"];

Second option:

detailImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"noimageavailable" ofType:@"jpg"]];

I noticed that after loading another image which is available from the server, the noimageavailable.jpg is still appeared behind the new image, which means noimageavailable.jpg is cached somehow. I got the same result with the two options imageNamed: and imageWithContentsOfFile APIs.

Here is my completed code:

        if (detailImageURL.length == 0) {
            detailImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"noimageavailable" ofType:@"jpg"]];
//Once displayed, it's cached for all lifecycle


        }else{

        dispatch_async(DownloadQueue, ^{

            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:detailImageURL]];
                dispatch_async(dispatch_get_main_queue(), ^{

                    detailImageView.image = nil;
                    UIImage *image = [UIImage imageWithData:imageData];
                    detailImageView.image = image;
                });
    });
    }

Any way to clear cache?

Upvotes: 0

Views: 3757

Answers (2)

B.S.
B.S.

Reputation: 21726

About these 2 methods

+ (UIImage *)imageNamed:(NSString *)name

This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

The is no way to clear this cache

+ (UIImage *)imageWithContentsOfFile:(NSString *)path

This method does not cache the image object.

But i think, that your case does not depends on any images cache and you do not replace the images, but every time create new imageView and add it on the previous.

Upvotes: 5

Jake Spencer
Jake Spencer

Reputation: 1127

Is it possible that you are adding multiple separate UIImageViews? I.e. you are adding a local variable named detailImageView to your superview one time when this method is called, and then later on you call this method again and a new local variable UIImageView named detailImageView is added to the superview on top of the old one? If this is this case, you should see [self.view.subviews count] increasing as the method is called multiple times, adding multiple UIImageViews. In that case, you need to remove the old UIImageView before adding a new one.

Upvotes: 0

Related Questions