数据持久化之app沙盒属性文件
self.plistFilePath = [self applicationDocumentsDirectoryFile];
//初始化属性列表文件
- (void)createPropertyListFileIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL dbexits = [fileManager fileExistsAtPath:self.plistFilePath];
if (!dbexits) {
int method = 2;
//法1通过app工程里副本文件创建
if(method == 1){
//1.获得当前类所在的NSBundle对象
NSBundle *frameworkBundle = [NSBundle bundleForClass:[ self class]];
NSString *frameworkBundlePath = [frameworkBundle resourcePath];
NSString *defaultDBPath = [frameworkBundlePath stringByAppendingPathComponent:@“dataList.plist"];
NSError *error;
//1.1 将副本文件移动到沙盒
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:self.plistFilePath error:&error];
if (error) {
NSAssert(success, @"错误写入文件");
}
}
//法2 创建一个空文件
else if(method == 2) {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
//2.将空文件写入沙盒文件(也可以将新建,修改,删除后的数据写入到文件)<不一定用数组,也可以用字典保存>
[array writeToFile:self.plistFilePath atomically:TRUE];
}
}
}
- (NSString *)applicationDocumentsDirectoryFile {
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) lastObject];
NSString *path = [documentDirectory stringByAppendingPathComponent:@"dataList.plist"];
return path;
}
如果你发现本文对你有所帮助,如果你认为其他人也可能受益,请把它分享出去。