CoreData永久保存?

问题描述:

我一直在iPad应用程序中使用Core Data,我可以在应用程序内成功保存和获取数据。但是,当完全关闭应用程序时,完全退出,将其从多任务中取出,并且数据消失。CoreData永久保存?

中也是如此核心数据无论如何,当应用程序被关闭的任何地方保持这些数据?或者我需要去别的地方看看?

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

这是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); 
    } 
+0

你如何设置你的managedObjectContext?为了在退出后保存数据,您需要设置一个NSPersistentStoreCoordinator。 – DerekH 2010-11-30 22:01:49

+0

更新的问题与更多细节。 – 2010-11-30 22:25:03

+1

你的保存代码是完全错误的。除非调用`-save:`返回NO,否则绝对不能*查看`saveError`的值。这样做是编程错误,并可能导致应用程序崩溃。 `-save:`不保证将该变量保留为有效值,除非返回NO。所以你应该使用`if(![context_ save:&saveError]){/ * read saveError * /}`。 – 2010-12-01 21:36:29

。事实证明,由于其使用的UIDatePicker的,在程序的开始使用它设置日期选取到今天:

NSDate *now = [[NSDate alloc] init]; 
[datePicker setDate:now]; 

所以不使用这个它完美的作品。所以目前我正在寻找这个问题的解决方案,因为这条线似乎导致了这个问题。

UIDatePicker Interfering with CoreData

您应该发布设置您的NSPersistentStoreCoordinator的代码并添加您的NSPersistentStore。您有没有机会使用NSInMemoryStoreType作为您店铺的类型?因为那会导致你看到的行为。或者,您每次都可以使用与商店不同的路径,这样每次都会为您提供全新的商店。一般来说,您的商店应该位于您的Documents文件夹中,并且每次启动时都应该使用相同的名称。它也应该使用NSSQLiteStoreType

你保存上下文在正确的地方?当仅在willTerminate中进入后台应用程序状态时,不保存上下文是常见的错误。

保存在下面的appdelegate方法的上下文:

-(void)applicationDidEnterBackground:(UIApplication *)application 

您直接插入对象后,保存您的背景下,这应该是足够了。如果保存后包含任何数据,请检查模拟器中的sqlite文件。

如果

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

不抛出异常,有在上下文中找到的对象。也许它不包含预期值? 从fetchrequest登录返回的对象安慰,看看这可能是我已经发现了问题的情况下

如果添加CoreData后,即可制作project.There是犯错误的lazy_init您NSManagedObject的风险。

-(NSManagedObjectContext*) managedObjectContext{ 
if (!_managedObjectContext) { 
    _managedObjectContext =[self createManageObjectContextWithName:@"name.sqlite"]; 
} 
return _managedObjectContext;} 

这是正确的做法:

- (NSManagedObjectContext *)managedObjectContext { 
if (_managedObjectContext != nil) { 
    return _managedObjectContext; 
} 

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 
if (!coordinator) { 
    return nil; 
} 
_managedObjectContext = [[NSManagedObjectContext alloc] init]; 
[_managedObjectContext setPersistentStoreCoordinator:coordinator]; 
return _managedObjectContext;}