NSData writeToFile成功写入Plist,但随后崩溃,给出NSInvalidArgumentException

编程入门 行业动态 更新时间:2024-10-22 10:37:18
本文介绍了NSData writeToFile成功写入Plist,但随后崩溃,给出NSInvalidArgumentException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用新的NSJSONSerialization类和NSPropertyListSerialization类将JSON文件转换为plist.我设法将JSON正确地转换为Plist,但是,在最后一步,当我将plist写入桌面时,程序崩溃了,但是在生成Plist之后!

I am converting a JSON file to a plist using the new NSJSONSerialization class and NSPropertyListSerialization class. I manage to convert my JSON to a Plist without errors, but then, at my last step, when I go to write the plist to my desktop, the program crashes, but AFTER the Plist has been generated!

NSData *data = [[NSData alloc] initWithContentsOfURL:path]; \\(NSURL *)path -->goes to my JSON file NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; //the following removes all key/object pairs where the object is null, because NSPropertyListSerialization with throw an error if there are null values for (id __strong object in [json objectForKey:@"terms"]) { if ([object objectForKey:@"image"] == [NSNull null]) { [object removeObjectForKey:@"image"]; } } //the following NSPropertyListSerialization method returns an NSData id plist = [NSPropertyListSerialization dataFromPropertyList:(id)json format:NSPropertyListXMLFormat_v1_0 errorDescription:nil]; NSError *writeToFileError; [plist writeToFile:@"/Users/kalaracey/Desktop/test.plist" atomically:YES encoding:NSUTF8StringEncoding error:&writeToFileError];

然后,在这最后一行,抛出NSInvalidArgumentException,并使我的程序崩溃.但是,plist已成功生成!我可以阅读,一切都很好,除了我的程序崩溃了.

Then, at this last line, an NSInvalidArgumentException is thrown, and crashes my program. However, the plist was successfully generated! I can read it, and all is well, except my program crashes.

有人可以解释一下为什么崩溃,以及如何避免崩溃吗?

Could someone please explain why this crashes, and how I could avoid crashing?

推荐答案

问题似乎是变量plist的类型为id.将其强制转换为NSData,您应该没问题.

The problem seems to be that the variable plist is type id. Cast it to NSData and you should be fine.

NSData *plist = (NSData *) [NSPropertyListSerialization ...];

正如您在注释中正确指出的那样,NSData应该使用writeToFile:atomically:方法.

As you correctly point out in the comment, NSData should use the writeToFile:atomically: method.

更多推荐

NSData writeToFile成功写入Plist,但随后崩溃,给出NSInvalidArgumentException

本文发布于:2023-11-26 17:14:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:writeToFile   NSData   NSInvalidArgumentException   Plist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!