首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NSData缓存iOS

NSData缓存iOS
EN

Stack Overflow用户
提问于 2016-08-05 02:11:25
回答 1查看 568关注 0票数 1

我正在开发一个类似snapchat的应用程序,我正在尝试缓存图像和视频的NSData表示。我尝试了NSCache,但这不起作用,每次应用程序转到后台时,缓存中的所有对象都会被移除,然后我尝试使用NSUserDefaults进行缓存,但这也不是一个好方法。虽然它的工作和数据持久化使用NSUserDefaults,但它占用大量内存,我读到在这个类中存储这种类型的对象是不好的做法。除了上面提到的两个之外,你还有什么关于缓存和持久化数据的建议?

EN

回答 1

Stack Overflow用户

发布于 2016-08-05 02:22:07

将NSData写入应用程序的文档目录中,并在应用程序中再次需要该数据时读取该数据

用于向应用程序的文档目录写入数据的

代码语言:javascript
运行
复制
//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]);
}

用于从应用程序的文档目录读取数据的

代码语言:javascript
运行
复制
/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]);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38774528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档