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

2020-01-16  本文已影响0人  数字d

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

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);
上一篇下一篇

猜你喜欢

热点阅读