ios

iOS数据持久化——文件读写(plist)

2017-03-02  本文已影响341人  伯牙呀

⽂件读写(序列化)是最简单的数据持久化方式。
plist文件是将某些特定的类,通过XML文件的方式保存在目录中。

读写方法

NSDictionary 为例,其他类使用方法完全相似:

+ (void)saveUserInfotoLocalWithDic:(NSDictionary *)dic {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *dicPath = [documentPath stringByAppendingPathComponent:@"myUserInfo.plist"];
    NSFileManager* fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:dicPath]) {
       BOOL rrr = [fm createFileAtPath:dicPath contents:nil attributes:nil];
        if (rrr) {
            NSLog(@"创建文件成功");
        } else {
            NSLog(@"创建文件失败");
        }
    }
    // 序列化,把字典存入plist文件
    BOOL ret = [dic writeToFile:dicPath atomically:YES];
    if (!ret) {
        NSLog(@"写入本地失败");
    }
}

+ (NSDictionary *)getUserInfofromLocal {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *dicPath = [documentPath stringByAppendingPathComponent:@"myUserInfo.plist"];
    // 反序列化,把plist文件数据读取出来,转为字典
    NSDictionary *userInfoDic = [NSDictionary dictionaryWithContentsOfFile:dicPath];
    return userInfoDic;
}

NSDictionary-plist文件的存取过程:

NSDictionary-plist文件的存取过程

可以被序列化的类型只有如下几种:

NSArray;//数组
NSMutableArray;//可变数组
NSDictionary;//字典
NSMutableDictionary;//可变字典
NSData;//二进制数据
NSMutableData;//可变二进制数据
NSString;//字符串
NSMutableString;//可变字符串
NSNumber;//基本数据
NSDate;//日期

对于复杂对象(自定义类)无法在程序内通过 writeToFile: 这个方法直接写入到文件内,需要通过 NSKeyedArchiver

有时候会遇到字典写入本地失败情况:

上一篇 下一篇

猜你喜欢

热点阅读