Ios 应用程序关闭时,NSURLCache将清空

Ios 应用程序关闭时,NSURLCache将清空,ios,objective-c,afnetworking,nsurlcache,Ios,Objective C,Afnetworking,Nsurlcache,我正在尝试使用AFHTTPRequestOperation实现NSURLCache,这就是我所做的: AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 dis

我正在尝试使用AFHTTPRequestOperation实现NSURLCache,这就是我所做的:

AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:50 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];

....
    }
然后,为了使用它,我会这样做:

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0f];
UIImage *image = [[UIImageView sharedImageCache] cachedImageForRequest:urlRequest];
if (image != nil) {
  //Cached image
} else {

AFHTTPRequestOperation *postOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
postOperation.responseSerializer = [AFImageResponseSerializer serializer];
[postOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  UIImage *image = responseObject;
  [[UIImageView sharedImageCache] cacheImage:image forRequest:urlRequest];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  NSLog(@"Image error: %@", error);
}];
[postOperation start];
}

当上面有代码时,我第一次打开视图下载图像并将其存储在缓存中,然后我关闭视图并再次打开它并从缓存中读取,如果我关闭应用程序并重试,图像将再次下载,那么我如何创建NSURLCache持久性

编辑:

我尝试了Duncan Bubbage的建议,我添加了一个缓存路径,而不是nil,我是这样做的:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    cachePath = [cachePath stringByAppendingPathComponent:@"temp_img"];

    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:50 * 1024 * 1024 diskPath:cachePath];
    [NSURLCache setSharedURLCache:URLCache];

但我仍然无法在整个会话中快速缓存,我错了什么?我还检查了Finder中的缓存文件夹,其中有temp\u img文件夹,我尝试使用NSFileManager手动创建文件夹,然后传递路径,但文件夹temp\u img仍然为空…

当您希望跨会话持久缓存到磁盘时,是否确定设置
diskPath:nil
有效?该参数是可选的,但这可能仅适用于仅在内存中缓存的用例,在这种情况下,您希望看到您在这里看到的内容

或者,各国:

在iOS中,当系统磁盘空间不足时,可能会清除磁盘缓存,但只有在应用程序未运行时才会清除


这可能是预期的行为?

感谢您的回答,当系统内存不足时,我必须清除磁盘上的缓存,或者iOS自动清除?如果整个系统(不仅仅是您的缓存)的可用磁盘空间不足,iOS将自动清除。我已尝试添加路径,但不起作用,我已更新问题在应用程序运行时,是否有任何内容写入缓存目录,然后被删除,或者只是没有写入内容?没有写入内容,没有目录,没有图像。请确保路径存在。如果我使用nsfilemanager创建它,请确保确实存在,但文件夹始终为空,另外,文档中说,如果文件夹不存在,它将被创建,因此我认为这不是问题所在,任何人都可以帮助我?使用MemoryCapacity:0设置init有效吗?尝试将内存容量设置为与磁盘容量相同的大小。可能是内存容量阻止了缓存的使用。在这方面,您的问题在这里陈述“当上面有代码时,我第一次打开视图下载图像并将其存储在缓存中”。但是,您是否确实确认过该图像曾经被缓存过,或者即使在当前应用程序会话期间也会被重新下载?可能只是因为缓存根本不工作。