I’m working on a rss reader. It is just a tableview and each cell shows a custom data model RSSEntry. And I have a NSMutableArray allEntries which contains all RSSEntry I got from the server. This is what RSSEntry looks like:
@interface RSSEntry : NSObject <NSCoding> {
NSString *_blogTitle;
NSString *_articleTitle;
NSString *_articleUrl;
NSDate *_articleDate;
}
I want to restore data from local archive so when I quit and open this app again, the tableview is populated with data when last refresh.
I’ve read example in ‘Beginning iOS5 Programming’, but it only store and restore only one data model. So I don’t know how to store this mutable array full of my custom data model and restore it.
I use following code to store and restore data:
// STORE
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:entry forKey:kDataKey];
[archiver finishEncoding];
// RESTORE
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath:kFilename]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
RSSEntry *entries = [unarchiver decodeObjectForKey:kDataKey];
[unarchiver finishDecoding];
I can only store and restore one data model in this way.
Who can give me a hand. I’m new to iOS programming, maybe it’s a little dull .sorry.
Place all the entries you want to store into an
NSArrayand use this code:Where
entriesis your array of entries. Nice and easy, just one line of code.To unarchive, just use
NSKeyedArchiveris able to archive any data structure, even a very complex one, of Objective-C objects that implement theNSCodingprotocol, including nestedNSArrays,NSDictionarys, and custom objects, to a file.NSKeyedUnarchiverdoes the reverse, taking any data produced byNSKeyedArchiverand reestablishing the original object graph that was archived. Technically, they could just be a single class, but Apple decided to separate them by functionality because this is more grammatically correct or something 🙂I assume you are able to write the resulting
NSDataobject to a file, and read it back again.