0

如何让我的应用程序在关闭时存储信息。因为每次我重新打开它,所有的核心数据都会被删除。

这是一个例子:

NSString *nomville = [[_jsonDict objectAtIndex:indexPath.row] objectForKey:@"label"];
NSString *idVille = [[_jsonDict objectAtIndex:indexPath.row] objectForKey:@"id"];

detailView.title = nomville;
detailView.idVille = idVille;

NSLog(@"Valor: %@", nomville);
NSLog(@"Valor: %@", idVille);

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *villesR = [NSEntityDescription
                                   insertNewObjectForEntityForName:@"Ville"
                                   inManagedObjectContext:context];
[villesR setValue:idVille forKey:@"idV"];
[villesR setValue:nomville forKey:@"nom"];

[self.navigationController pushViewController:detailView animated:YES];
4

1 回答 1

1

当您的应用程序被推送到后台或退出时,您通常会调用保存方法。

你可以在你的应用委托中这样做:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self saveContext];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [self saveContext];
}

#pragma mark - Core Data stack

- (void)saveContext {
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}
于 2012-06-08T09:50:34.563 回答