一.数据持久化之app沙盒属性文件保存

数据持久化之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;
}

如果你发现本文对你有所帮助,如果你认为其他人也可能受益,请把它分享出去。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容