How do I serialize an object to file using NSKeyedArchiver in NSPropertyListXMLFormat_v1_0 format?

StackOverflow https://stackoverflow.com/questions/726053

Question

Hopefully that title is clear enough. Anyways, it seems:

[NSKeyedArchiver archiveRootObject:rootObject toFile:path];

is restricted to NSPropertyListBinaryFormat_v1_0.

I need the format to be human readable [so xml]. If you're interested, this is part of project I'll eventually put up on github with a blog post about "How to Unit Test GPS Applications"

:-)

Was it helpful?

Solution

You have to use NSPropertyListSerialization to convert it. Basically, assuming the object that you're serializing is called myObject and the ultimate file is stored in myPath, you would serialize it to XML using something like the following code fragment:

NSString *error = nil;
NSData *mySerializedObject = [NSKeyedArchiver archivedDataWithRootObject:myObject];
NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:mySerializedObject
                        format:NSPropertyListXMLFormat_v1_0
                        errorDescription:&error]:
if( xmlData ) {
    [xmlData writeToFile:myPath atomically:YES];
} else {
    NSLog(error);
    [error release];
}

OTHER TIPS

Instead of using the class method, try creating an instance of NSKeyedArchiver and using setOutputFormat:NSPropertyListXMLFormat_v1_0 to specify XML format. The only downside is it'll take a few extra lines of code since to actually handle the serialization, it won't just return an NSData object in one step.

You will have to encode the object class by using method -(void) encodeWithCoder(NSCoder *)encoder {

[coder encodeObject:name forKey:@"name"];
[coder encodeObject:address forKey:@"address"];
[coder encodeObject:position forKey:@"position"];

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top