NSData writeToFile成功写入Plist,但随后崩溃,给出NSInvalidArgumentException [英] NSData writeToFile writes Plist successfully, but then crashes, giving 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!