3

I have an NSDictionary, which contains a bunch of NSManagedObjects. I can then use NSKeyedArchiver to write this to an NSData object. These are generated using this method. Which works fine and allows me to save a section of schema to disc and then read it back as a new set of objects in the core data model. If I use either archivedDataWithRootObject: or archiveRootObject:toFile:, as per the documentation I can see that the format of the archive is NSPropertyListBinaryFormat_v1_0, whereas I want to serialise in NSPropertyListXMLFormat_v1_0, so that I can write my objects to a file and then process them elsewhere as plain old XML. (In fact I want to generate documents from them on a Windows based system.)

1) Is there a way I can do this? If so how? 2) Is there a better approach.

I want to maintain the serialised nature, since I also want to send the file back to the iOS device later and recreate the object model.

Will Johnston
  • 864
  • 4
  • 18

2 Answers2

3
  1. Create your own instance of NSKeyedArchiver with initForWritingWithMutableData:.
  2. Set the format with setOutputFormat:NSPropertyListXMLFormat_v1_0.
  3. Encode your root object with encodeObject:forKey:.
  4. Call finishEncoding.

To unarchive the data you encoded in this way, you have to similarly instantiate an NSKeyedUnarchiver.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
1

Thanks Ole! I was heading in that direction, but was not sure if it was the right way. Here is what I did in code in case it helps someone.

NSDictionary *dataAsDictionary=[self toDictionaryBlockingRelationships:blockRelationship];
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
NSMutableData *xmlData=[NSMutableData data];

NSKeyedArchiver *archive=[[NSKeyedArchiver alloc ]initForWritingWithMutableData:xmlData];

[archive setOutputFormat:NSPropertyListXMLFormat_v1_0];
[archive encodeRootObject:dataAsDictionary];
[archive finishEncoding];

if(![xmlData writeToFile:savePath atomically:NO]){
    NSLog(@"Failed to write to file to filePath=%@", savePath);
}
[archive release];
Will Johnston
  • 864
  • 4
  • 18