Question

For the sake of simplicity, let's assume that we have the following simple class interface:

@interface Person : NSObject <NSCoding> {
  NSString *firstname;
  NSString *lastname;
}

@property (copy) NSString *firstname;
@property (copy) NSString *lastname;

@end

Is it possible to serialize this object into a plist (assuming that the NSCoding protocol is implemented correctly)?

Update December, 31st 2010 14:40

I have some follow up questions on this. Is it possible to have NSKeyedArchiver export the plist as XML? Furthermore, is it possible to dump the XML into variable instead of a file?

Was it helpful?

Solution

As for setting the output format to XML, I suggest:

[myKeyedArchiver setOutputFormat: NSPropertyListXMLFormat_v1_0];

As for getting it into a variable and not a file, I would suggest creating your NSKeyedArchiver with the initForWritingWithMutableData: initializer. Once finished encoding, make sure to call finishEncoding on it, and then the XML will be in the NSMutableData that you passed in at init time.

If you then need to get an NSString from that, you can get that from your NSMutableData like so:

NSString* xmlString = [[NSString alloc] initWithData: myMutableData  encoding: NSUTF8StringEncoding];

That should do the trick. Good luck!

OTHER TIPS

Yes, it is. However, its not really convenient as you have to encode the object first and then save the NSData object into the array/dictionary which you want to save into the plist.

NSKeyedArchiver will automatically save the object to a plist when you give it a filename.plist file path.

This appears to be a defect in iOS. I am wondering if it is specific to the handling of the user defaults plist though.

As a possible workaround, perhaps you could try managing an NSMutableDictionary for your settings and read/write the dictionary as a plist file directly.

To write the data:

NSString* error;
NSData* pListData = [NSPropertyListSerialization dataFromPropertyList:settingsDictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
[data writeToFile:settingsFilePath atomically:YES];

Then to read the data back:

NSString* error;
NSData* pListData = [NSData dataWithContentsOfFile:settingsFilePath];
settingsDictionary = [NSPropertyListSerialization propertyListFromData:pListData mutabilityOption:NSPropertyListImmutable format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

Try this magic:

NSData* data = [NSKeyedArchiver archivedDataWithRootObject:person];

plist[@"personData"] = data;

To get it back out just use:

Person* p = [NSKeyedUnarchiver unarchiveObjectWithData:plist[@"personData"]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top