iOS 开发之字典写入文件

在最近的开发中阿,遇到一个问题,是我开始没有注意到的问题,某个羡慕后期维护的过程中发现一个bug,这个bug就是关于字典写入文件的。缘由是这样的,我用字典写入文件的方法

BOOL result = [resultDic writeToFile:CityListDataPath atomically:YES];

    if (result) {

        NSLog(@"HYH-写入成功");

    }else {

        NSLog(@"HYH-写入失败");

    }

 至于这个问题我通过阅读官方文档找到了答案,官方文档是这么说的:

Discussion

This method recursively validates that all the contained objects are property list objects (instances of NSDataNSDateNSNumberNSStringNSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

If the dictionary’s contents are all property list objects, the file written by this method can be used to initialize a new dictionary with the class method dictionaryWithContentsOfFile: or the instance method initWithContentsOfFile:.

意思是说只有属性列表类型是以上红色部分的类型才能被正确的写入到文件中。由于开始开发时候,后台返回的数据是没null类型的,但是现在反回的部分参数value是null这就导致了写入文件失败的情况,那么由于后台是有可能变动的,而dictionary的写入方法又是有限制,那么该如如何解决这个问题呢?一种方式就是让后台切莫反悔null,但是这种方式太。。恩有点勉强;那么我认为比较好的方式就是将其转换为Data然后写入文件:

 NSDictionary *resultDic = [data objectForKey:@"data"];

    NSData *resultData = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:nil];

    BOOL result = [resultData writeToFile:CityListDataPath atomically:YES];

    if (result) {

        NSLog(@"HYH-写入成功");

    }else {

        NSLog(@"HYH-写入失败");

    }

解析:

NSData *data = [NSData dataWithContentsOfFile:CityListDataPath];

    NSDictionary * resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

这种方式就会很好的避免了后台返回数据对我们程序的影响了!

原文地址:https://www.cnblogs.com/wannaGoBoy/p/5757032.html