通常情况下, 我们想写收藏功能时, 需要通过数据库来存到本地, 因为数据比较多。那么,当我们想要将一些少的数据保存到本地时,就没有必要写入到数据库那么麻烦,只需要通过写入沙盒中就可以实现。当然,两种存储到本地的方法都可以实现大数据和小数据的存储,只是简单与复杂的关系。下面是存到沙盒的具体过程。
写入到本地沙盒中:
代码:这里的ModelForWeather 是一个自定义用来存储接口解析出来的model 数据。
// 要归档的对象.
ModelForWeather *model = self.arrayForChoosePlace[indexPath.row];
// 创建归档时所需的data 对象.
NSMutableData *data = [NSMutableData data];
// 归档类.
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// 开始归档(@"model" 是key值,也就是通过这个标识来找到写入的对象).
[archiver encodeObject:model forKey:@"model"];
// 归档结束.
[archiver finishEncoding];
// 写入本地(@"weather" 是写入的文件名).
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"weather"];
[data writeToFile:file atomically:YES];
这样就可以将网络请求的数据存到沙盒中。
从沙盒中读出:
代码:
// 从本地(@"weather" 文件中)获取.
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"weather"];
// data.
NSData *data = [NSData dataWithContentsOfFile:file];
// 反归档.
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// 获取@"model" 所对应的数据
ModelForWeather *model = [unarchiver decodeObjectForKey:@"model"];
// 反归档结束.
[unarchiver finishDecoding];
这样就可以把我们存入的数据从沙盒中取出来使用了。
网友评论