Object serialization in XML format using Obj-C / iPhone SDK
I have an iPhone App that uses a relatively small amount of data. I'd like to save开发者_如何学Python the data in the XML format and be able to load this in memory to Objective-C objects. I'd like to use iPhone SDK facilities like NSPropertyListSerialization or writeToFile:atomically: classes and methods.
The NSPropertyListSerialization documentation says that
The NSPropertyListSerialization class provides methods that convert property list objects to and from several serialized formats. Property list objects include NSData, NSString, NSArray, NSDictionary, NSDate, and NSNumber objects.
Suppose I'd like to save a couple of Person objects (a family) whose attributes are all property-list types. The only-way I managed to save this in XML Format is by doing:
// container for person objects
NSMutableArray *family = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfPeople; i++) {
// simulate person's attributes
NSArray *keys = [[NSArray alloc] initWithObjects:
@"id",
@"name",
@"age",
Nil];
NSArray *values = [[NSArray alloc] initWithObjects:
[NSNumber numberWithInt:i],
@"Edward",
[NSNumber numberWithInt:10],
Nil];
// create a Person (a dictionary)
NSDictionary *person = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
[family addObject:person];
[person release];
}
// save the "person" object to the property list
[family writeToFile:@"<path>/family.plist" atomically:YES];
[family release];
which would generate the family.plist file.
Note, however, that my Person object is actually a NSDictionary object (which I don't think subclassing would be a good idea) with attributes as keys. Is there any way to create a Objective-C class like this:
@interface Person : NSObject {
NSString *_id;
NSString *_name;
NSNumber *_age;
}
@end
and serialize it to a plist/XML file? (I need to save the object in text format (not binary) so that I can edit such data in a text editor and allow my application to load this at runtime, converting to Objective-C objects normally).
Thanks in advance, Eduardo
If you haven't already read it, I would highly recommend the Archives and Serializations Programming Guide, particularly the parts about encoding and decoding objects using the NSCoding protocol.
If you use that protocol, your objects will be stored as NSData. But you could imitate it (i.e. create your own protocol) so that your classes return dictionary representations of themselves, and can initialize themselves from a dictionary representation (I don't think there's a way to automatically do that). However, the result would essentially be the same as the family.plist file you posted.
If you're looking for a way to get an XML file like this:
<person>
<id>0</id>
<name>Edward</name>
<age>10</age>
</person>
then plist isn't what you want.
I am ashamed to say that I use [NSString stringWithformat:]
to make XML documents. It is the easiest way I have found so far.
精彩评论