Skip to content

Instantly share code, notes, and snippets.

@andkon
Last active December 31, 2015 23:29
Show Gist options
  • Save andkon/8060711 to your computer and use it in GitHub Desktop.
Save andkon/8060711 to your computer and use it in GitHub Desktop.
Adding serialized permanent data storage to an iOS app
@interface ADKAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) NSMutableDictionary *storageDict;
-(NSString *)filePath;
@end
static ADKAppDelegate *launchedDelegate;
@implementation AppDelegate
- (NSString *)filePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.archive"];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// This is where you decode the data you store.
launchedDelegate = self;
NSString *filePath = [self filePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
self.storageDict = [unarchiver decodeObjectForKey:@"dictToSerializeAndSave"];
}
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// This is where you encode the data you store.
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self.storageDict forKey:@"storageDict"];
[archiver finishEncoding];
NSError *error = nil;
NSString *filePath = [self filePath];
BOOL success = [data writeToFile:filePath options:NSDataWritingAtomic error: &error];
if (!success) {
NSLog(@"writeToFile failed with error %@", error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment