ios 沙盒和常见的数据存储方式。

沙盒是系统为了ios程序分配的可以读写数据的文件区域。

沙盒位于计算机中的位置:/user/本机用户/library/application surpport/iphone simulator/7.0/applictions 找到我们的应用程序,并在其中找到GUID文件夹。

沙盒里面有三个重要的文件夹:

1documents:用于存储NSUesrDefults之外的数据。

2tmp用于存储临时数据,当数据不再需要的时候我们将删除数据。

3library:NSUserDefults的数据保存在LIbrary/Preferences下面。

三个重要文件夹的获取

documents:

[NSSearchPathForDirectoriesInDomain(NSDocumentDirectorty,NSUserDomainMask,YES)lastobject];//第一个参数要求返回的是dcument,返回的数据是一个数组

tmp:

NSTemporaryDirectory();

library:

他的访问方式不需要使用路径,他是通过[NSUesrDefults standardUserDefults]对象的 setXXX:forkey:和XXXforkey:方法以键值对的形式存取数据。这算作一种数据的存储方式。



其他的数据存储方式:

plist:

将数组写入文件:

    NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];
    NSString *fullPath=[path stringByAppendingPathComponent:@"text.plist"];
    NSArray *plistArray=@[@"1",@"3",@"15"];
    [plistArray writeToFile:fullPath atomically:YES];//atomically这个参数意思是如果为YES则保证文件的写入原子性,就是说会先创建一个临时文件,直到文件内容写入成功再导入到目标文件里.如果为NO,则直接写入目标文件里
    NSLog(@"%@",[NSArray arrayWithContentsOfFile:fullPath]);

将字典写入文件:

    NSDictionary *plistDict=@{@"1":@"one",@"5":@"five"};
    [plistDict writeToFile:fullPath atomically:YES];
    NSLog(@"%@",[NSDictionary dictionaryWithContentsOfFile:fullPath]);

归档:(自定义的数据结构)

在自定义数据结构的时候我们要重写他的两个方法

写入时候调用:

-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_age forKey:@"age"];
    [aCoder encodeObject:_name forKey:@"name"];
}
取值时调用:

-(id)initWithCoder:(NSCoder *)decoder
{
    self=[super init];
    if (self) {
        [self setAge:[decoder decodeObjectForKey:@"age"]];<pre name="code" class="objc">    NSArray *modelModel=@[model,model1];
    [NSKeyedArchiver archiveRootObject:modelModel toFile:modelPath];
    NSArray *arraymodel=[NSKeyedUnarchiver unarchiveObjectWithFile:modelPath];

[self setName:[decoder decodeObjectForKey:@"name"]]; } return self;}

 

可以利用归档方法对这个自定义数据进行存取:

    NSString *modelPath=[path stringByAppendingPathComponent:@"model.data"];
    PersonModel *model=[[PersonModel alloc] init];
    model.age=@(19);
    model.name=@"lilei";
    [NSKeyedArchiver archiveRootObject:model toFile:modelPath];
    PersonModel *getModel=[NSKeyedUnarchiver unarchiveObjectWithFile:modelPath];

亦可以将模型放到一个数组中一块进行归档:

    NSArray *modelModel=@[model,model1];
    [NSKeyedArchiver archiveRootObject:modelModel toFile:modelPath];
    NSArray *arraymodel=[NSKeyedUnarchiver unarchiveObjectWithFile:modelPath];




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值