iOS 常用数据存储之NSKeyedArchiver(归档)

在实际的项目中,数据存储是每个软件开发者不可避免会涉及到的话题。对于iOS开发者而言,我们首先关心的就是app是把数据存储在哪里的。

一.关于沙盒机制。

和Android系统不同的是,iOS系统使用的是特有的数据安全策略:沙盒机制。所谓沙盒机制是指:系统会为每个APP分配一块独立的存储空间,用于存储图像,图标,声音,映像,属性列表,文本等文件,并且在默认情况下每个APP只能访问自己的空间。

怎么查看模拟器中APP的沙盒的目录结构?
在程序中执行如下语句,得到沙盒的路径:

NSLog(@"%@",NSHomeDirectory());

打印的结果是:

 /Users/XXX/Library/Developer/CoreSimulator/Devices/41D208F9-4E93-48EC-A254-10EA246048DF/data/Containers/Data/Application/8AD61414-4125-408A-B0FF-DE451973E2C8

在Finder中,Finder>前往>前往文件夹。将上面打印出的路径张贴到输入框内,然后点击前往。就会出现如下内容:

沙盒目录结构.png

我们可以看到三个文件夹:Documents, Library, tmp。

  1. Documents: 用于保存应用运行时生成的需要持久化、非常大的或者需要频繁更新的数据,iTunes会自动备份该目录 .
    //获取目录位置的代码如下
    NSArray *documentDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //上面的documentDirectory是只有一个元素的数组,还需要以下代码取出路径
    NSString *myDocPath = [documentDirectory objectAtIndex:0];
    //或者 NSString *myDocPath = [documentDirectory lastObject];
  2. Libaray: 用于存储程序的默认设置和其他状态信息,iTunes会自动备份该目录。Libaray/下主要有两个文件夹:Libaray/Caches和Libaray/Preferences。
    //获取目录位置的代码如下:
    NSArray *libraryDirectory = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
    NSString * libraryDirectory = [libraryDirectory lastObject];
  1. Libaray/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除,一般存放体积比较大,不是很重要的资源。
    //获取目录位置的代码如下:
    NSArray *cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *cachesDirectory = [cachesDirectory lastObject];
  1. Libaray/Preferences:保存应用的所有偏好设置,ios的Settings(设置)应用会在该目录中查找应用的设置信息,iTunes会自动备份该目录。
    //获取目录位置的代码如下:
    NSArray * preferencesDirectory = NSSearchPathForDirectoriesInDomains(NSPreferencesDirectory,NSUserDomainMask,YES);
    NSString * preferencesDirectory = [preferencesDirectory lastObject];
  2. tmp: 保存应用运行时所需的临时数据,使用完毕后再将相应的文件从该目录删除,应用没有运行时,系统也可能会自动清理该目录下的文件,iTunes不会同步该目录,iPhone重启时该目录下的文件会丢失。
    //获取目录位置的代码如下:
    NSString *tmp = NSTemporaryDirectory();

既然存的地方清楚了,我们接下来聊聊iOS常见的存储方式:

二.常见的存储方式。

我们常见的有四种存储方式:用NSUserDefaults存储配置信息 ,用NSKeyedArchive归档的形式来保存对象数据, 文件沙盒存储 , 数据库存储 。

1. 用NSUserDefaults存储配置信息

该方法被设计用来存储设备和应用的配置、属性、用户的信息,它通过一个工厂方法返回默认的实例对象。它实际上是存储于文件沙盒中的一个.plist文件,并且没有被系统加密,只是ios6以后不是存于常用的文档目录下,所以不破解系统是看不到。
该文件的可以存储的数据类型包括:NSData、NSString、NSNumber、NSDate、NSArray、NSDictionary。如果要存储其他类型,则需要转换为前面的类型,才能用NSUserDefaults存储。

用该方式存数据的代码如下 :

 NSString *teleNum =  @"1868XX23763"; 
 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
 [userDefaults setObject: teleNum forKey:@"teleNum"];

用该方式取数据的代码如下 :

 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
 NSString *teleNum = [userDefaults objectForKey:@"teleNum"]];
2. 文件沙盒存储

主要存储非机密数据,大的数据,如图片。

存文件的操作步骤如下:

(1). 获得文件即将保存的路径
方法一:

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask,YES);
NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

方法二:

NSString *sandboxPath = NSHomeDirectory();
NSString *documentPath = [sandboxPath
        stringByAppendingPathComponent:@"Documents"];

(2). 生成在该路径下的文件

NSString *FileName=[documentDirectory stringByAppendingPathComponent:fileName];//fileName就是保存文件的文件名 

(3). 往文件中写入数据

[data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件,文件名为FileName
从沙盒中取出文件:

取就比较简单,只需下面一行代码!

NSData data=[NSData dataWithContentsOfFile:FileName options:0 error:NULL];//从FileName中读取出数据
3. 用NSKeyedArchive归档的形式来保存对象数据

由于笔者暂时没有用过数据库存储,所以就不在这里帮门弄斧了。如文章题目,今天主要想谈的是第三种方法,即用NSKeyedArchive归档。下面将用一个简单的项目来讲解。

使用情景:在我们的实际开发过程中,为了更好的用户体验,可能需要在APP上存储用户的某些信息,比如淘宝APP会记录用户曾经填写过的收货地址。这种数据不方便用前面提到的NSUserDefaults来存储:一是,因为地址数据是一个模型,NSUserDefaults只能用于NSString、NSArray、NSDictionary等常用的数据类型;二是,用户还会经常对它进行增删改等操作,NSUserDefaults无法满足。
此时,用NSKeyedArchive归档的形式来存储地址模型数据最符合要求。

效果图.png
(1)创建地址模型CLVoiceApplyAddressModel

CLVoiceApplyAddressModel.h文件

#import <Foundation/Foundation.h>

@interface CLVoiceApplyAddressModel : NSObject<NSCoding>
//用于存储多个地址时,标记用户选中的状态
@property (nonatomic, copy) NSString *state;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phoneNum;
@property (nonatomic ,copy) NSString *mainAddress;
@property (nonatomic ,copy) NSString *detailAddress;

+(instancetype)AddressModelWithDict:(NSDictionary *)dict;
-(instancetype)initAddressModelWithDict:(NSDictionary *)dict;
@end

CLVoiceApplyAddressModel.m文件

  #import "CLVoiceApplyAddressModel.h"

  @implementation CLVoiceApplyAddressModel

-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_state forKey:@"state"];
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_phoneNum forKey:@"phoneNum"];
    [aCoder encodeObject:_mainAddress forKey:@"mainAddress"];
    [aCoder encodeObject:_detailAddress forKey:@"detailAddress"];
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
    self.state= [aDecoder decodeObjectForKey:@"state"];
    self.name = [aDecoder decodeObjectForKey:@"name"];
    self.phoneNum = [aDecoder decodeObjectForKey:@"phoneNum"];
    self.mainAddress = [aDecoder decodeObjectForKey:@"mainAddress"];
    self.detailAddress = [aDecoder decodeObjectForKey:@"detailAddress"];
}else{
    return nil;
}
return self;
}
+(instancetype)AddressModelWithDict:(NSDictionary *)dict{
return [[self alloc] initAddressModelWithDict:dict];
}

-(instancetype)initAddressModelWithDict:(NSDictionary *)dict{
if (self = [super init]) {
    self.state =[dict objectForKey:@"state"];
    self.name =[dict objectForKey:@"name"];
    self.phoneNum =[dict objectForKey:@"phoneNum"];
    self.mainAddress =[dict objectForKey:@"mainAddress"];
    self.detailAddress =[dict objectForKey:@"detailAddress"];
}
return self;
}
@end

为了实现对归档地址的操作,我们专门创建了一个工具类:CLInvoiceApplyAddressModelTool。

#import <Foundation/Foundation.h>
@class CLVoiceApplyAddressModel;

@interface CLInvoiceApplyAddressModelTool : NSObject

+(NSArray *)allAddressInfo;
+(CLVoiceApplyAddressModel *)currentSelectedAddress;
+(void)update;
+(void)updateAddressInfoAfterDeleted;

+(void)setSelectedAddressByNewInfoArray:(NSArray *)infoArray;
+(void)addInfo:(CLVoiceApplyAddressModel *)info;
+(void)removeInfoAtIndex:(NSUInteger)index;
+(void)updateInfoAtIndex:(NSUInteger)index withInfo:(CLVoiceApplyAddressModel *)info;
+(void)removeAllInfo;
@end


#import "CLInvoiceApplyAddressModelTool.h"
#import "CLVoiceApplyAddressModel.h"
#define AddressInfosPath  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"addressInfo1.data"]

@implementation CLInvoiceApplyAddressModelTool
static NSMutableArray *_addressInfos;
+(NSArray *)allAddressInfo{
    _addressInfos = [NSKeyedUnarchiver unarchiveObjectWithFile:AddressInfosPath];
    if (!_addressInfos) _addressInfos = [NSMutableArray array];
    return _addressInfos;
}
+(CLVoiceApplyAddressModel *)currentSelectedAddress{
    CLVoiceApplyAddressModel *currentAddress;
BOOL hasSelectedAddress = NO;
if ([self allAddressInfo].count) {
    for (CLVoiceApplyAddressModel *info in _addressInfos) {
        if ([info.state isEqualToString:@"1"]) {
            currentAddress = info;
            hasSelectedAddress = YES;
            break;
        };
    }
}else if([self allAddressInfo].count == 0 || hasSelectedAddress)
{
    currentAddress = nil;
}
return currentAddress;
}
+(void)update{
[NSKeyedArchiver archiveRootObject:_addressInfos toFile:AddressInfosPath];
}
+(void)updateAddressInfoAfterDeleted{
if (_addressInfos.count) {
    if (![self currentSelectedAddress]) {
        CLVoiceApplyAddressModel *info = [CLInvoiceApplyAddressModelTool allAddressInfo][0];
        info.state = @"1";
        [CLInvoiceApplyAddressModelTool updateInfoAtIndex:0 withInfo:info];
    }
}
  }
+(void)setSelectedAddressByNewInfoArray:(NSArray *)infoArray{
[NSKeyedArchiver archiveRootObject:infoArray toFile:AddressInfosPath];
}
+(void)addInfo:(CLVoiceApplyAddressModel *)info{
if (!_addressInfos.count) {
    _addressInfos = [NSMutableArray array];
}
for (CLVoiceApplyAddressModel *oldInfo in _addressInfos ) {
    oldInfo.state = @"0";
}
[_addressInfos insertObject:info atIndex:0];
[self update];
}
+ (void)removeInfoAtIndex:(NSUInteger)index {
[_addressInfos removeObjectAtIndex:index];
[self update];
}
+ (void)removeAllInfo{
[_addressInfos removeAllObjects];
[self update];
}
+ (void)updateInfoAtIndex:(NSUInteger)index withInfo:(CLVoiceApplyAddressModel *)info {
[_addressInfos replaceObjectAtIndex:index withObject:info];
[self update];
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,392评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,258评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,417评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,992评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,930评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,199评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,652评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,327评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,463评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,382评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,432评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,118评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,704评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,787评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,999评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,476评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,057评论 2 341

推荐阅读更多精彩内容