I have an iPhone App that uses a relatively small amount of data. I'd like to save 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