如何清除IOS应用程序库缓存(下载的图像)

问题描述:

我正在处理下载异步图像。我从我的网络服务器获得了很多图像,但都是暂时的,我不会缓存它们中的任何一个。但该应用程序显然将下载图像保存在/ Library / Caches中。我该如何解决?

I am working with download async images. I get a lot images from my webserver but all are temporary and I won't cache any of them. But the app apparently save the download images in /Library/Caches. How can I resolve that?

有没有办法阻止缓存下载的图像?或者从缓存中删除它们?

Are there any way to prevent cache downloaded images? Or delete them from cache?

我尝试了这两种不同的方法:

I tried these two different methods:

#pragma mark - Method 1

- (void)method1{
    NSURL *imageURL = [NSURL URLWithString:self.photoLink];
    [self setImage:[UIImage imageNamed:@"nut"] forState:UIControlStateNormal];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:imageURL options:NSDataReadingUncached error:NULL];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
            });
        });
    //}
}

#pragma mark - Method 2

- (void)method2{

    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    // The Placeholder
    [self setImage:[UIImage imageNamed:@"nut"] forState:UIControlStateNormal];

    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                            selector:@selector(loadDataAsyc)
                                                                              object:nil];
    [queue addOperation:operation];

    [operation release];
}
-(void)loadDataAsyc{

    // create a local autorelease pool since this code runs not on main thread
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.photoLink] options:NSDataReadingUncached error:NULL];
    UIImage *image = [UIImage imageWithData:data];

    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:NO];

    [pool release];
}
-(void)showImage:(UIImage *)image{
    [self setImage:image forState:UIControlStateNormal];
}


缓存将在清空时清空它需要,即当应用程序收到低内存警告时。您没有理由自己这样做,并且没有可用的公共API。

The cache will be emptied when it needs to be, i.e. when the application receives a Low Memory Warning. There is no reason for you to do this yourself, and there is no public API available.

注意

当操作系统为您管理某些内容时,您无需担心。

但如果你真的想清除你的缓存,那就按照这个

But if you really want to clear your cache then follow this

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr removeItemAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] error: NULL]  == YES)
    NSLog (@"Remove successful");
else
    NSLog (@"Remove failed");

[filemgr createDirectoryAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] withIntermediateDirectories:NO attributes:nil error:nil];