In my app, I retrieve url data from the server. As an optimization, I normalize the data by storing it into a custom class so that the data can be quickly accessed later on. However, I need to store an instance of this class locally and offline so that I can avoid retrieving data from the server if I've already done so. Also, the website changes daily, so the cached data is only useful if it's from the same day.
This scenario applies to 2 separate classes (4 objects in total), and I've tried saving this data with NSCoding like so. (I've only tried implementing 1 object so far, but I'm planning on creating a separate docPath for each object)
- (void) saveStateToDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
[fileMan removeItemAtPath:docPath error:&error];
// Store the hours data
Hours *h = [self parseHoursFromServer];
NSDictionary *state = [NSDictionary dictionaryWithObjectsAndKeys:h, @"Hours", nil];
// There are many ways to write the state to a file. This is the simplest
// but lacks error checking and recovery options.
[NSKeyedArchiver archiveRootObject:state toFile:docPath];
NSLog(@"end");
}
- (NSDictionary*) stateFromDocumentNamed:(NSString*)docName
{
NSError *error;
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths[0] stringByAppendingPathComponent:docName];
if ([fileMan fileExistsAtPath:docPath])
return [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
return nil;
}
However, when I tried running this code, I received a [Hours encodeWithCoder:]: unrecognized selector sent to instance 0
because my class currently does not support NSCoding. After reading about how I need to manually encode all the properties for my custom class, I want to make sure that NSCoding is an ideal solution to my data caching problem.
EDIT:
Here is how I currently create the url
NSURL *url = [NSURL URLWithString:urlString];
NSData *pageData = [NSData dataWithContentsOfURL:url];