Last active
December 31, 2015 23:29
-
-
Save andkon/8060711 to your computer and use it in GitHub Desktop.
Adding serialized permanent data storage to an iOS app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface ADKAppDelegate : UIResponder <UIApplicationDelegate> | |
@property (strong, nonatomic) NSMutableDictionary *storageDict; | |
-(NSString *)filePath; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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