CoreData永久保存?

发布于 2024-10-05 10:50:26 字数 4147 浏览 0 评论 0原文

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

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

编辑:这是在应用程序委托 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);
    }

I have been working with Core Data in an iPad app and I can successfully save and fetch data inside the app. However when completely closing the application, fully, quit, take it out of multitasking, and that data disappears.

So does Core Data in anyway keep this data anywhere when the app is closed? Or do I need to look somewhere else?

EDIT: This is in the app delegate didFinishLaunchingWithOptions: [[[UIApplication sharedApplication] delegate] managedObjectContext]; and then I have this: context_ = [(prototypeAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; in the UIView subclass.

This is the NSPersistentStoreCoordinator code premade in the app delegate:

- (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_;
}

So far I am using this to fetch data:

    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"];

And this to save data:

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);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

简单 2024-10-12 10:50:26

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

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

-(void)applicationDidEnterBackground:(UIApplication *)application

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

如果

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

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

Do you save the context in the right places? It is a common mistake not to save the context when entering background application state only in willTerminate.

Save the context in the following appdelegate method:

-(void)applicationDidEnterBackground:(UIApplication *)application

You are saving your context directly after inserting the object, this should be sufficient. Check the sqlite file in simulator if it contains any data after saving.

if

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

does not throw an exception, there is an object found in context. Maybe it does not contain the expected value?
Log the returned object from your fetchrequest to console to see if this might be the case

明媚殇 2024-10-12 10:50:26

您应该发布设置 NSPersistentStoreCoordinator 并添加 NSPersistentStore 的代码。您是否有可能使用 NSInMemoryStoreType 作为商店的类型?因为这会导致您所看到的行为。或者,您可以每次使用不同的路径到达商店,这样每次都会给您一个新的商店。一般来说,您的商店应该位于您的文档文件夹中,并且每次启动时都应该指定相同的名称。它还应该使用 NSSQLiteStoreType

You should post the code that sets up your NSPersistentStoreCoordinator and adds your NSPersistentStore. By any chance are you using NSInMemoryStoreType as the type of your store? Because that would result in the behavior you're seeing. Alternately, you could be using a different path to the store each time, which would give you a fresh store each time. In general, your store should be in your Documents folder, and it should be given the same name on every launch. It should also use the NSSQLiteStoreType

始终不够 2024-10-12 10:50:26

我已经发现了问题所在。事实证明,由于它使用了 UIDatePicker,因此在程序开始时它使用以下命令将日期选择器设置为今天:

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

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

UIDatePicker 干扰 CoreData

I have discovered the problem. It turns out that due to its use of UIDatePicker, at the start of the program it set that date picker to today using:

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

So without using this it works perfectly. So currently I am looking for a solution to this issue, as this line seems to cause the problem.

UIDatePicker Interfering with CoreData

┾廆蒐ゝ 2024-10-12 10:50:26

如果您在创建项目后添加 CoreData,则 NSManagedObject 的lazy_init 中存在出错的风险。

-(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;}

If you add a CoreData after create your project.There is a risk to make mistake in lazy_init your NSManagedObject.

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

Here is the right way:

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

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
    return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文