您的位置:首页 > 移动开发 > IOS开发

深入讲解iOS开发中应用数据的存储方式

2015-12-11 09:27 1071 查看

XML属性列表-plist
一、应用沙盒
每个iOS应用都有⾃己的应⽤沙盒(应用沙盒就是文件系统目录),与其他文件系统隔离。应⽤必须待在⾃己的沙盒里,其他应用不能访问该沙盒(提示:在IOS8中已经开放访问)

应⽤沙盒的文件系统⽬录,如下图所示(假设应用的名称叫Layer)

模拟器应⽤用沙盒的根路径在: (apple是⽤用户名, 7.0是模拟器版本) /Users/apple/Library/Application Support/iPhone Simulator/7.0/Applications

二、应用沙盒结构分析

应⽤程序包:(上图中的Layer)包含了所有的资源文件和可执行文件

Documents:保存应⽤运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录。例如,游戏应用可将游戏存档保存在该目录

tmp:保存应⽤运行时所需的临时数据,使⽤完毕后再将相应的文件从该目录删除。应用没有运行时,系统也可能会清除该目录下的文件。iTunes同步设备时 不会备份该目录

Library/Caches:保存应用运行时⽣成的需要持久化的数据,iTunes同步设备时不会备份该目录。⼀一般存储体积大、不需要备份的非重要数据

Library/Preference:保存应用的所有偏好设置,iOS的Settings(设置) 应⽤会在该⺫录中查找应⽤的设置信息。iTunes同步设备时会备份该目录

三、应用沙盒常见的获取方式

沙盒根目录:NSString *home = NSHomeDirectory();
 Documents:(2种⽅方式)

利用沙盒根目录拼接”Documents”字符串

复制代码 代码如下:
NSString *home = NSHomeDirectory();
NSString *documents = [home stringByAppendingPathComponent:@"Documents"]; // 不建议采用,因为新版本的操作系统可能会修改目录名

利用NSSearchPathForDirectoriesInDomains函数
复制代码 代码如下:
// NSUserDomainMask 代表从用户文件夹下找
// YES 代表展开路径中的波浪字符“~”
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO); // 在iOS中,只有一个目录跟传入的参数匹配,所以这个集合里面只有一个元素

NSString *documents = [array objectAtIndex:0];

tmp:NSString *tmp = NSTemporaryDirectory();


Library/Caches:(跟Documents类似的2种⽅方法)

利用沙盒根目录拼接”Caches”字符串

利⽤NSSearchPathForDirectoriesInDomains函数(将函数的第2个参数改 为:NSCachesDirectory即可)

Library/Preference:通过NSUserDefaults类存取该目录下的设置信息

相应的代码:

复制代码 代码如下:
#import "NJViewController.h"
#import "NJPerson.h"

@interface NJViewController ()
- (IBAction)saveDataBtnClick:(id)sender;
- (IBAction)readDataBtnClick:(id)sender;

@end


复制代码 代码如下:
@implementation NJViewController
/**
 *   点击保存按钮
 */
- (IBAction)saveDataBtnClick:(id)sender {
   
    // youtube做法
//    NSString *path = @"/Users/apple/Library/Application Support/iPhone Simulator/7.1/Applications/A6D53E11-DDF0-4392-B2D4-FE77A96888A6/Documents/abc.plist";
   
    // 获取应用程序根目录
    NSString *home = NSHomeDirectory();
   
    // 不建议写/
    //NSString *path = [home stringByAppendingString:@"/Documents"];
    // 不建议Documents写死
    //NSString *path = [home stringByAppendingPathComponent:@"Documents"];
   
    // NSUserDomainMask 在用户目录下查找
    // YES 代表用户目录的~
    // NSDocumentDirectory 查找Documents文件夹
    // 建议使用如下方法动态获取
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 拼接文件路径
    NSString *path = [doc stringByAppendingPathComponent:@"abc.plist"];
    NSLog(@"%@", path);
   
   
    //NSArray *arr = @[@"lnj", @"28"];
    //[arr writeToFile:path atomically:YES];
   
    // NSDictionary *dict = @{@"name": @"lnj", @"age":@"28"};
    // 调用writeToFile将数据写入文件
    // [dict writeToFile:path atomically:YES];
    
    /*
     plist只能存储系统自带的一些常规的类, 也就是有writeToFile方法的对象才可以使用plist保存数据
     字符串/字典/数据/NSNumber/NSData ...
     */
   
    // 自定义的对象不能保存到plist中
    NJPerson *p = [[NJPerson alloc] init];
    p.name =@"lnj";
   
    NSDictionary *dict = @{@"person": @"abc"};
    [dict writeToFile:path atomically:YES];
}
/**
 *   点击读取按钮
 */
- (IBAction)readDataBtnClick:(id)sender {
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
   
    NSString *path = [doc stringByAppendingPathComponent:@"abc.plist"]
    ;
    // 读取数据
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSLog(@"%@", dict);
}
@end

四、属性列表

属性列表是一种XML格式的文件,拓展名为plist

如果对象是NSString、NSDictionary、NSArray、NSData、 NSNumber等类型,就可以使用writeToFile:atomically:⽅法 直接将对象写到属性列表文件中


NSKeydeArchiver归档
一、简单说明

在使用plist进行数据存储和读取,只适用于系统自带的一些常用类型才能用,且必须先获取路径相对麻烦;
偏好设置(将所有的东西都保存在同一个文件夹下面,且主要用于存储应用的设置信息)
归档:因为前两者都有一个致命的缺陷,只能存储常用的类型。归档可以实现把自定义的对象存放在文件中。
二、代码示例

1.文件结构

复制代码 代码如下:
//
//  YYViewController.m
//  02-归档
//
//  Created by apple on 14-6-7.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYViewController.h"
#import "YYPerson.h"

@interface YYViewController ()
- (IBAction)saveBtnOnclick:(id)sender;
- (IBAction)readBtnOnclick:(id)sender;

@end


复制代码 代码如下:
@implementation YYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}


- (IBAction)saveBtnOnclick:(id)sender {
    //1.创建对象
    YYPerson *p=[[YYPerson alloc]init];
    p.name=@"文顶顶";
    p.age=23;
    p.height=1.7;
   
    //2.获取文件路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
    NSLog(@"path=%@",path);
   
    //3.将自定义的对象保存到文件中
    [NSKeyedArchiver archiveRootObject:p toFile:path];
   
}

- (IBAction)readBtnOnclick:(id)sender {
    //1.获取文件路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
    NSLog(@"path=%@",path);
   
    //2.从文件中读取对象
    YYPerson *p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@,%d,%.1f",p.name,p.age,p.height);
}
@end


新建一个person类

YYPerson.h文件

复制代码 代码如下:
//
//  YYPerson.h
//  02-归档
//
//  Created by apple on 14-6-7.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import <Foundation/Foundation.h>

// 如果想将一个自定义对象保存到文件中必须实现NSCoding协议
@interface YYPerson : NSObject<NSCoding>

//姓名
@property(nonatomic,copy)NSString *name;
//年龄
@property(nonatomic,assign)int age;
//身高
@property(nonatomic,assign)double height;
@end


YYPerson.m文件
复制代码 代码如下:
//
//  YYPerson.m
//  02-归档
//
//  Created by apple on 14-6-7.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYPerson.h"

@implementation YYPerson

// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    NSLog(@"调用了encodeWithCoder:方法");
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    [aCoder encodeDouble:self.height forKey:@"height"];
}

// 当从文件中读取一个对象的时候就会调用该方法
// 在该方法中说明如何读取保存在文件中的对象
// 也就是说在该方法中说清楚怎么读取文件中的对象
-(id)initWithCoder:(NSCoder *)aDecoder
{
    NSLog(@"调用了initWithCoder:方法");
    //注意:在构造方法中需要先初始化父类的方法
    if (self=[super init]) {
        self.name=[aDecoder decodeObjectForKey:@"name"];
        self.age=[aDecoder decodeIntegerForKey:@"age"];
        self.height=[aDecoder decodeDoubleForKey:@"height"];
    }
    return self;
}
@end


3.打印效果和两个重要的错误提示

点击保存按钮和读取按钮,成功打印结果如下:

关于不实现两个协议方法的错误提示:

-(void)encodeWithCoder:(NSCoder *)aCoder方法:

-(id)initWithCoder:(NSCoder *)aDecoder方法:

三、继承类中的使用

新建一个学生类,让这个类继承自Preson这个类,增加一个体重的属性。

YYstudent.h文件

复制代码 代码如下:
//
//  YYstudent.h
//  02-归档
//
//  Created by apple on 14-6-7.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYPerson.h"

@interface YYstudent : YYPerson
//增加一个体重属性
@property(nonatomic,assign) double weight;
@end


YYstudent.m文件
复制代码 代码如下:
//
//  YYstudent.m
//  02-归档
//
//  Created by apple on 14-6-7.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYstudent.h"

@implementation YYstudent

//在子类中重写这两个方法
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [super encodeWithCoder:aCoder];
    NSLog(@"调用了YYStudent encodeWithCoder");
    [aCoder encodeFloat:self.weight forKey:@"weight"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        NSLog(@"调用了YYstudent initWithCoder");
        self.weight = [aDecoder decodeFloatForKey:@"weight"];
    }
    return self;
}
@end


YYViewController.m文件
复制代码 代码如下:
//
//  YYViewController.m
//  02-归档
//
//  Created by apple on 14-6-7.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYViewController.h"
#import "YYPerson.h"
#import "YYstudent.h"

@interface YYViewController ()
- (IBAction)saveBtnOnclick:(id)sender;
- (IBAction)readBtnOnclick:(id)sender;

@end


复制代码 代码如下:
@implementation YYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}


- (IBAction)saveBtnOnclick:(id)sender {
    //1.创建对象
//    YYPerson *p=[[YYPerson alloc]init];
//    p.name=@"文顶顶";
//    p.age=23;
//    p.height=1.7;
    
    YYstudent *s=[[YYstudent alloc]init];
    s.name=@"wendingding";
    s.age=23;
    s.height=1.7;
    s.weight=62;
    //2.获取文件路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
    NSLog(@"path=%@",path);
   
    //3.将自定义的对象保存到文件中
//    [NSKeyedArchiver archiveRootObject:p toFile:path];
     [NSKeyedArchiver archiveRootObject:s toFile:path];
   
}

- (IBAction)readBtnOnclick:(id)sender {
    //1.获取文件路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
    NSLog(@"path=%@",path);
   
    //2.从文件中读取对象
//    YYPerson *p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
//    NSLog(@"%@,%d,%.1f",p.name,p.age,p.height);
    YYstudent *s=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@,%d,%.1f,%f",s.name,s.age,s.height,s.weight);
}
@end


点击保存按钮和读取按钮后的打印输出:

四、重要说明

1.保存数据过程:

复制代码 代码如下:
//1.创建对象
    YYstudent *s=[[YYstudent alloc]init];
    s.name=@"wendingding";
    s.age=23;
    s.height=1.7;
    s.weight=62;
    
    //2.获取文件路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
    NSLog(@"path=%@",path);
   
    //3.将自定义的对象保存到文件中
     [NSKeyedArchiver archiveRootObject:s toFile:path];

2.读取数据过程:
复制代码 代码如下:
//1.获取文件路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
    //2.从文件中读取对象
    YYstudent *s=[NSKeyedUnarchiver unarchiveObjectWithFile:path];

3.遵守NSCoding协议,并实现该协议中的两个方法。

4.如果是继承,则子类一定要重写那两个方法。因为person的子类在存取的时候,会去子类中去找调用的方法,没找到那么它就去父类中找,所以最后保存和读取的时候新增加的属性会被忽略。需要先调用父类的方法,先初始化父类的,再初始化子类的。

5.保存数据的文件的后缀名可以随意命名。

6.通过plist保存的数据是直接显示的,不安全。通过归档方法保存的数据在文件中打开是乱码的,更安全。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS 应用 存储