美文网首页
iOS文件操作,字典写入json文件

iOS文件操作,字典写入json文件

作者: 数字d | 来源:发表于2020-01-16 12:01 被阅读0次

    担心表述不清楚,直接上代码地址

    https://gitee.com/xgkp/filewrite.git

    1.构造字典

        NSDictionary * dic = @{@"key":@"value"};
    
    

    2.设置文件夹路径

        NSString * basicCachePath = GETDEFAULTS(HP_LocaCache_BasicDir);
        //根路径文件夹directoryName,可自己修改
        NSString* directoryName = @"basicDir";
        NSString* cachePath = [HPFileManager cacheDirectory];
        BOOL isDirectory;
        BOOL result = [HPFileManager fileExistInPath:basicCachePath isDirectory:&isDirectory];
        if (result) {
        }else
        {
            BOOL createResult = [HPFileManager createDirectoryInPath:cachePath directoryName:directoryName];
            if (createResult) {
                NSString * path = [NSString stringWithFormat:@"%@/%@",cachePath,directoryName];
                basicCachePath = path;
                SAVEDEFAULTS(path, HP_LocaCache_BasicDir)
            }else
            {
                NSLog(@"创建文件夹失败!");
                return;
            }
        }
    

    3.创建.json文件,获取文件路径

    String * name = @"name";
        NSString * fileName = [NSString stringWithFormat:@"%@.json",name];
        if (fileExist1 && isi) {
            NSString * filePath = [basicCachePath stringByAppendingPathComponent:fileName];
            fileUsePath = filePath;
        }
    

    4.将字典存入json文件中

        SAVEDEFAULTS(fileUsePath, HP_DetailPath);
        [HPFileManager saveDictionary:dic isPlistFileOfPath:fileUsePath];
    

    5.获取json文件的路径,并取出json文件中的字典

       NSString * path = GETDEFAULTS(HP_DetailPath);
        //真机调试模式下,打印一下path的值,用命令行vim 接路径可以查看文件内容
        NSDictionary * dic = [HPFileManager dictionaryInPlistFileOfPath:path];
        NSLog(@"%@",dic);
    

    相关文章

      网友评论

          本文标题:iOS文件操作,字典写入json文件

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