(三十九)数据的持久化存储-plist实现(XML属性表)

iOS应用数据存储的常用方式:

归档:用某种格式保存数据。

XML属性列表(plist)归档(持久化)

Preference 偏好设置

NSKeyedArchiver归档

SQLite3 数据库 效率最高

缺点是SQLite是关系型数据库,将对象存入数据库需要将对象进行转码(使用SQL语句)

Core Data 苹果官方提供的对SQLite数据库操作的封装


应用沙盒:

每个应用之间是隔开的,不能相互访问。

应用沙盒的目录结构:

Layer放资源包。

Documents保存运行生成的需要持久化的数据,iTunes会自动备份,例如游戏存档。

tmp保存应用运行时的临时数据,使用完毕的可能会被删除。

Library/Caches保存运行时生成的存储体积大、不需要备份的数据,iTunes不会备份这个目录。

Library/Preference保存所有的偏好设置,iOS的Settings应用会在该目录中查找应用的设置信息,iTunes会将其备份。


利用plist来存储数据:

注意一个细节,使用string的Path...方法可以避免写路径斜杠,提高兼容性。

    NSString *homePath = NSHomeDirectory(); // 获取沙盒根路径
    NSString *docPath = [homePath stringByAppendingPathComponent:@"Documents"];
    NSArray *data = @[@"ele1",@2,@"ele3"];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"data.plist"];
    [data writeToFile:filePath atomically:YES];
数据的读取:

    NSString *homePath = NSHomeDirectory();
    NSString *docPath = [homePath stringByAppendingPathComponent:@"Documents"];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"data.plist"];
    NSArray *data = [NSArray arrayWithContentsOfFile:filePath];


缺点:系统自带的OC对象才能写入。



原文地址:https://www.cnblogs.com/aiwz/p/6154212.html