美文网首页
plist文件用法小结

plist文件用法小结

作者: 逝风不名 | 来源:发表于2017-08-16 13:44 被阅读128次
    1. 创建plist文件路径(一般保存到沙盒document文件夹中)
    //获取plist文件路径
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsPath = [path objectAtIndex:0];
        NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"user_phone.plist"];
    

    2.根据路径,创建或者取出plist文件内容(如果是数组用NSMutableArray去接,如果是字典就用NSMutableDictionary去接)

    //比如说根容器是个数组(字典同理)
    NSMutableArray * plistArray =nil;
        if (![[NSMutableArray alloc]initWithContentsOfFile:plistPath]) {
            //创建一个根容器为数组的plist文件
            plistArray = [NSMutableArray array];
            [plistArray writeToFile:plistPath atomically:YES];
        }else{
            plistArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        }
    

    3.关于plsit文件的一些操作(其实就是操作数组或字典,然后写入plist)

    • 添加一条数据(以添加账号密码为例)
    NSMutableDictionary * newsDict = [NSMutableDictionary dictionary];
        [newsDict setObject:@"1234567890" forKey:@"user_phone"];
        [newsDict setObject:@"123" forKey:@"user_pass"];
        [plistArray addObject:newsDict];
        [plistArray writeToFile:plistPath atomically:YES];
    
    • 修改一条数据
    for (NSDictionary * dict in plistArray) {
            if ([dict[@"user_phone"] isEqualToString:userPhone]) {
                [dict setValue:userPass forKey:@"user_pass"];
                [plistArray writeToFile:plistPath atomically:YES];
                 NSLog(@"%@",plistArray);
                return;
            }
        }
    
    • 删除一条数据
    NSMutableArray * plistArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
            for (int i = 0; i < plistArray.count; i++) {
                NSDictionary * dict = plistArray[i];
                if ([dict[@"user_phone"] isEqualToString:userPhone]) {
                    [plistArray removeObject:dict];
                    [plistArray writeToFile:plistPath atomically:YES];
                }
    }
    

    相关文章

      网友评论

          本文标题:plist文件用法小结

          本文链接:https://www.haomeiwen.com/subject/yhjirxtx.html