iphone - CoreData永久保存?

标签 iphone objective-c core-data load save

我一直在 iPad 应用程序中使用 Core Data,并且可以在应用程序内成功保存和获取数据。但是,当完全关闭应用程序、完全退出、退出多任务处理时,该数据就会消失。

那么当应用程序关闭时,核心数据是否会将这些数据保留在任何地方?或者我需要去别的地方看看吗?

编辑:这是在应用程序委托(delegate)didFinishLaunchingWithOptions中:[[[UIApplication sharedApplication] delegate] ManagedObjectContext];然后我有这个:context_ = [ (prototypeAppDelegate *)[[UIApplication sharedApplication] delegate] ManagedObjectContext]; 在 UIView 子类中。

这是在应用程序委托(delegate)中预制的 NSPersistentStoreCoordinator 代码:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator_ != nil) {
        return persistentStoreCoordinator_;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"prototype.sqlite"];

    NSError *error = nil;
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return persistentStoreCoordinator_;
}

到目前为止,我正在使用它来获取数据:

    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:context_];
    [fetch setEntity:testEntity];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
    [fetch setPredicate:pred];

    NSError *fetchError = nil;
    NSArray *fetchedObjs = [context_ executeFetchRequest:fetch error:&fetchError];
    if (fetchError != nil) {
        NSLog(@"fetchError = %@, details = %@",fetchError,fetchError.userInfo);
    }
    noteTextView.text = [[fetchedObjs objectAtIndex:0] valueForKey:@"savedText"];

这是为了保存数据:

NSManagedObject *newDatedText;
    newDatedText = [NSEntityDescription insertNewObjectForEntityForName:@"DatedText" inManagedObjectContext:context_];
    [newDatedText setValue:noteTextView.text forKey:@"savedText"];
    [newDatedText setValue:datePicker.date forKey:@"dateSaved"];

    NSError *saveError = nil;
    [context_ save:&saveError];
    if (saveError != nil) {
        NSLog(@"[%@ saveContext] Error saving context: Error = %@, details = %@",[self class], saveError,saveError.userInfo);
    }

最佳答案

您是否将上下文保存在正确的位置?仅在 willTerminate 中进入后台应用程序状态时不保存上下文是一个常见的错误。

在以下 appdelegate 方法中保存上下文:

-(void)applicationDidEnterBackground:(UIApplication *)application

您在插入对象后直接保存上下文,这应该足够了。保存后检查模拟器中的sqlite文件是否有数据。

如果

noteTextView.text = [[fetchedObjs objectAtIndex:0] valueForKey:@"savedText"];

不抛出异常,在上下文中找到了一个对象。也许它不包含预期的值? 将 fetchrequest 返回的对象记录到控制台,看看是否是这种情况

关于iphone - CoreData永久保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4319104/

相关文章:

iphone - 如何让自动对焦在第二个 AVCaptureSession 中工作而不重新创建 session ?

ios - 自定义呈现的 UIViewController 更改为全屏

ios - 将 NSThread 与 NSManagedObject 相关联

ios - 完善我的 MagicalRecord 导入

ios - iOS 7 上的 NS 合并冲突

iphone - 如何保存书签数据?

iphone - Segues 无法以编程方式工作

android - 后台发短信到自己的手机号,短信列表不显示已发短信

objective-c - iOS Core Data 如何使用谓词正确比较字符串文本?

ios - EXC_BAD_ACCESS 关于 mergeChangesFromContextDidSaveNotification