NSData writeToFile writes Plist successfully, but

2019-07-23 09:20发布

问题:

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];

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?

回答1:

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 ...];

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