数据持久化-写入plist

需要确定我们想要存入plist的格式,这里我以数组包字典的格式作为例子(格式可以自己选择,放发都是一样的)

写入plist

  • 创建内层字典
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
  • 将想要存入的信息添加到字典中(这里以字符串为例子)
[dictionary setObject:@"24K纯金洋" forKey:@"content"];
  • 获取document文件夹的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
  • 设置plist的路径
NSString *plistPath = [documentDirectory stringByAppendingPathComponent:@"yang.plist"];
  • 创建文件管理者
NSFileManager *fileManager = [[NSFileManager alloc] init];
  • 写入本地
//查看路径内是否有plist文件
//如果没有穿件一个
//如果有执行写入操作
if (![fileManager fileExistsAtPath:plistPath]) {
//如果创建失败,提示用户
        if (![fileManager createFileAtPath:plistPath contents:nil attributes:nil]) {
            NSAssert(NO, @"Failed to create file");
        }else{
        //如果成功,写入plist
            NSMutableArray *array = [NSMutableArray arrayWithObject:historyDic];
            [array writeToFile:plistPath atomically:YES];
        }
    }else{
    //如果路径内有plist文件,先将数组取出,添加新内容,再写入
        NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        [array addObject:historyDic];
        [array writeToFile:plistPath atomically:YES];
    }

取出plist

其实创建的时候已经有过取出的操作

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentation = [path objectAtIndex:0];

    [fileManager changeCurrentDirectoryPath:[documentation stringByExpandingTildeInPath]];
    NSString *historyPlistPath = [documentation stringByAppendingPathComponent:@"history.plist"];
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:historyPlistPath];

取出数组候可以对数组操作,一下内容都是基于取出plist的,所以下面的代码取出的部分就直接省略了

删除全部

if (array.count != 0) {
        if ([fileManager fileExistsAtPath:historyPlistPath]) {
            [array removeAllObjects];
            [array writeToFile:historyPlistPath atomically:YES];
        }
    }
  • 额!不够完整,我的项目中先在就用到这几个方法,有时间继续!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值