我正在开发一个类似snapchat的应用程序,我正在尝试缓存图像和视频的NSData表示。我尝试了NSCache,但这不起作用,每次应用程序转到后台时,缓存中的所有对象都会被移除,然后我尝试使用NSUserDefaults进行缓存,但这也不是一个好方法。虽然它的工作和数据持久化使用NSUserDefaults,但它占用大量内存,我读到在这个类中存储这种类型的对象是不好的做法。除了上面提到的两个之外,你还有什么关于缓存和持久化数据的建议?
发布于 2016-08-05 02:22:07
将NSData写入应用程序的文档目录中,并在应用程序中再次需要该数据时读取该数据
用于向应用程序的文档目录写入数据的
//get the path of our apps Document Directory(NSDocumentDirectory)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//the path is stored in the first element
NSString *path = [paths firstObject];
//append the name of our file to the path: /path/to/myimage.png
path = path = [path stringByAppendingPathComponent:@"myimage.png"];
//store any errors
NSError *error;
// Write NSData to Disk
BOOL success = [imageData writeToFile:path atomically:YES];
if(success){
NSLog(@"Success");
}else{
NSLog(@"Error: %@",[error localizedDescription]);
}
用于从应用程序的文档目录读取数据的
/get the path of our apps Document Directory(NSDocumentDirectory)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//the path is stored in the first element
NSString *path = [paths firstObject];
//append the name of our file to the path: /path/to/myimage.png
path = path = [path stringByAppendingPathComponent:@"myimage.png"];
//store any errors
NSError *error;
NSData *rawImage = [NSData dataWithContentsOfFile:path
options:NSDataReadingMappedIfSafe error:nil];
if(rawImage){
UIImage *image = [UIImage imageWithData:rawImage];
NSLog(@"%@",image);
}else{
NSLog(@"Error: %@",[error localizedDescription]);
}
https://stackoverflow.com/questions/38774528
复制相似问题