Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code snippet to save array data using NSKeyedArchiver
// save array data
- (void)saveArrayData {
NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithCapacity:365];
if (urgeArray != nil) {
[dataDict setObject:urgeArray forKey:@"events"]; // save the urges array
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"eventData"];
[NSKeyedArchiver archiveRootObject:dataDict toFile:filePath];
}
// restore event data
- (void)restoreUrgeDataArrayInitialized {
// look for saved data.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"eventData"];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSDictionary *savedData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if ([savedData objectForKey:@"events"] != nil) {
eventArray = [[NSMutableArray alloc] initWithArray:[savedData objectForKey:@"events"]];
} else {
NSLog(@"restoreEventData: NO SAVED DATA");
eventArray = [[NSMutableArray alloc] init];
}
} else {
NSLog(@"restoreEventData: NO FILE");
eventArray = [[NSMutableArray alloc] init];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.