⽂件读写(序列化)是最简单的数据持久化方式。
plist文件是将某些特定的类,通过XML文件的方式保存在目录中。
- 写操作:通常使用
writeToFile:atomically:
⽅法实现文件的写操作,其中atomically
表示是否需要先写入一个辅助文件,再把辅助文件拷贝到目标文件地址。这是更安全的写入文件方法,一般都写YES
。 - 读操作:用
initWithContentsOfFile
方法实现文件的读操作。
读写方法
以 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
。
有时候会遇到字典写入本地失败情况:
1、数据不符合要求,自定义类不能用
writeToFile
存储2、要存的字典里含有值是 “<null>” 的数据(里面有<null>)