So, I've realised that I need to use NSCoding to save my custom objects to a plist.
The part I'm struggling with is exactly how I do that after I've implemented the initWithCoder
and encodeWithCoder
methods. They return id
and void
respectively, so if they've converted my objects into NSData or whatever they do to them, where's the data, so I can save it?
I have the methods set up thusly:
- (id)initWithCoder:(NSCoder *)decoder { // Decode
if (self = [super init]) {
self.name = [decoder decodeObjectForKey:@"gameName"];
self.genre = [decoder decodeObjectForKey:@"gameGenre"];
self.rating = [decoder decodeObjectForKey:@"gameRating"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder { // Encode
[encoder encodeObject:self.name forKey:@"gameName"];
[encoder encodeObject:self.genre forKey:@"gameGenre"];
[encoder encodeObject:self.rating forKey:@"gameRating"];
}
Trying to figure out what the next steps are to get these objects (which are already in an NSMutableArray) saved to a .plist, and recalled when re-opening the app.
Any help appreciated!
Well, that depends on what you want to do. It's possible that NSKeyedArchiver
will be sufficient. Consider:
+ (NSData *)archivedDataWithRootObject:(id)rootObject
+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path
which takes a root object of an object graph and either creates a NSData object with the serialized data, or serializes the data to a file.
Then look at NSKeyedUnarchiver
which has these:
+ (id)unarchiveObjectWithData:(NSData *)data
+ (id)unarchiveObjectWithFile:(NSString *)path
I'm sure that will get you on your way toward your goal.
EDIT
I'm hitting an error when trying to (I think) tell it which array I want it to write. Getting "Expected identifier" on this line: [rootObject setValue:[self.dataController.masterGameList] forKey:@"games"]; – lukech
That's a KVC API. The archive/unarchive methods are class methods, so you just save your entire object graph with:
if (![NSKeyedArchiver archiveRootObject:self.dataController.masterGameList
toFile:myPlistFile]) {
// Handle error
}
and then you load it with:
self.dataController.masterGameList =
[NSKeyedUnarchiver unarchiveObjectWithFile:myPlistFile];