美文网首页
字典或数组writeToFile写入不成功原因及解决方式

字典或数组writeToFile写入不成功原因及解决方式

作者: AnnieAri | 来源:发表于2017-04-10 10:48 被阅读0次

    当使用字典或者数组写入 writeToFile:@"xx/xx.plist" atomically:true]; 返回值为NO 一般有两个原因:

    • 1.要写入的文件夹 没有写入权限.
    • 2.集合内不能存储自定义对象,也不能是null.
      If an array or dictionary contains objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the various property-list methods and functions.

    解决方式:

    简单的序列化一下就可以了:比如

     NSData *data = [NSJSONSerialization dataWithJSONObject:message options:0 error:NULL];
     [data writeToFile:@"xx/xx.json" atomically:true];
    

    这样字典或者数组里有空值 也可以存储

    如果字典里有自定义对象的话 可以使用归档:

    //obj是字典或者数组
    [NSKeyedArchiver archiveRootObject:obj toFile:@"xx/xx.archive"];
    

    但是一定要为你的自定义对象类遵守<NSCoding> 并且实现:

    - (void)encodeWithCoder:(NSCoder *)aCoder;
    - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;
    

    相关文章

      网友评论

          本文标题:字典或数组writeToFile写入不成功原因及解决方式

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