uchicago-mobi / 2015-Winter-Forum

8 stars 1 forks source link

Read/write files with NSCoder #154

Closed thomkel closed 9 years ago

thomkel commented 9 years ago

I'm missing something fundamental about using the NSCoding protocol archive/unarchive object information.

We are supposed to persist a user's favorite articles to disk using NSCoding protocols on a data class we created. I assume this means we create a data class for the favorite articles.

If so, for each new favorite article, do we create a separate file? Or do all the articles get saved to the same file?

If the same file, how do we parse the file to get all the objects?

So far I believe I'm successfully creating and saving to a file, but it appears that each time I try to save a new object, I overwrite whatever object is already there.

This is my sloppy code:

// when creating/saving object

Favorite *newFav = [[Favorite alloc] init];
newFav.favUrl  = self.linkItem[@"link"];

NSError* err = nil;
NSURL *docs = [[NSFileManager new] URLForDirectory:NSDocumentDirectory
                                          inDomain:NSUserDomainMask appropriateForURL:nil
                                            create:YES error:&err];

NSData* sessionData = [NSKeyedArchiver archivedDataWithRootObject:newFav];
NSURL* file = [docs URLByAppendingPathComponent:@"sessions.plist"];
[sessionData writeToURL:file atomically:NO];
NSLog(@"DOCS:%@",file);

// when unarchiving

NSError* err = nil;
NSURL *docs = [[NSFileManager new] URLForDirectory:NSDocumentDirectory
                                          inDomain:NSUserDomainMask appropriateForURL:nil
                                            create:YES error:&err];
 NSURL* file = [docs URLByAppendingPathComponent:@"sessions.plist"];

NSData* data = [[NSData alloc] initWithContentsOfURL:file];
Favorite *favorite = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"Retrieved:%@",favorite);
tabinks commented 9 years ago

You can implement it in different ways:

thomkel commented 9 years ago

Great. That's actually what I started to do, but wasn't sure I was on the right track.

Thank you!