NSData存储在某个地方

最近我创build了一个post: NSDatacaching例程

但是,现在我想要更具体的问题。

你看,我有“旋转木马”,这实际上是一个有7个图像的滚动视图。 当它第一次出现时,它会加载来自互联网的图像和自动滚动。

我的问题是,我不想每次滚动时加载图像。 幸运的是,在后台有一些“caching”机制。 所以,当它加载所有的图像,然后终止应用程序,然后启动没有互联网连接,所有的图像已经设置,所以,它从某处加载它。

有我使用的代码:

NSError *error; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", WEBSITE, mdl.imageSubUrl]] options:NSDataReadingUncached error:&error];; NSLog(@"data size0? %lu", (unsigned long)data.length); 

那就是。 您可能想要自己尝试,加载一些图像,然后以飞行模式重新启动应用程序,并检查字节长度。 即使当我search它时,也会有数据,并且有人说, dataWithContentsOfURL不会执行任何caching。

所以,我想要的只是检查,如果有数据,如果是,不要下载。 像这样的东西:

 if (haveData){ self.ivPic.image = [UIImage imageWith:myData]; } else { NSError *error; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", WEBSITE, mdl.imageSubUrl]] options:NSDataReadingUncached error:&error];; NSLog(@"data size0? %lu", (unsigned long)data.length); } 

不幸的是,我不知道如何做这样的testing(如果有数据的话)。 其次,我不太清楚如何加载存储的数据,而不是dataWithContentsOfURL,它将从主机启动加载。

如果你自己做这个,你可以使用NSCache和本地文件系统创build双层caching系统。 所以,

  1. 在应用程序启动时,实例化一个NSCache对象。

  2. 当您需要下载图像时,请查看图像是否在NSCache

  3. 如果不是,请查看映像是否位于文件系统的NSCachesDirectory文件夹中,如果在这里find,但不在NSCache ,请确保相应地更新NSCache

  4. 如果在NSCacheNSCachesDirectory ,则从networkingasynchronous请求(使用NSURLSession ),如果成功find映像,则相应地更新NSCacheNSCachesDirectory

  5. 顺便说一句,根据UIApplicationDidReceiveMemoryWarningNotification ,确保清空NSCache

这可能看起来像这样:

 NSString *filename = [webURL lastPathComponent]; NSURL *fileURL; // look in `NSCache` NSData *data = [self.cache objectForKey:filename]; // if not found, look in `NSCachesDirectory` if (!data) { NSError *error; NSURL *cacheFileURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error]; fileURL = [cacheFileURL URLByAppendingPathComponent:filename]; data = [NSData dataWithContentsOfURL:fileURL]; // if found, update `NSCache` if (data) { [self.cache setObject:data forKey:filename]; } } // if still not found, retrieve it from the network if (!data) { [[NSURLSession sharedSession] dataTaskWithURL:webURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { // handle error return; } UIImage *image = [UIImage imageWithData:data]; // if image retrieved successfully, now save it if (image) { dispatch_async(dispatch_get_main_queue(), ^{ [self.cache setObject:data forKey:filename]; NSError *fileError; [data writeToURL:fileURL options:NSDataWritingAtomic error:&fileError]; }); } }]; } 

说了这一切,我同意其他人认为值得尝试在SDWebImage和/或AFNetworking中find的UIImageView类别。 他们可能会做你所需要的,而且工作less得多。

  • 首先,你应该检查types:
  • 得到这个链接:我给我的答案在这里: 检查NSData类的类的存储?

    希望这可以帮助你。