简体   繁体   English

核心数据不会在应用启动之间保留数据

[英]Core Data is not persisting data between app launches

I have a app that is using core data. 我有一个使用核心数据的应用程序。 The Core Data stack (the context, object graph, persistent store coordinator, and the persistent store) is being created, and I am able to use it without issue. 正在创建核心数据堆栈(上下文,对象图,持久性存储协调器和持久性存储),并且我可以毫无问题地使用它。 The problem is that the saved data is not persisting, can someone help me with what I am doing wrong? 问题是保存的数据无法持久保存,有人可以帮我解决我做错的事情吗? Here is where I create the Core Data stack. 这是我创建核心数据堆栈的地方。

- (void)initializeCoreDataStack
{
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Favorites"
                                              withExtension:@"momd"];
    if (!modelURL)
        NSLog(@"MODEL URL NOT INITIALIZED");

    NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    if (!mom)
        NSLog(@"OBJECT MODEL NOT CREATED");

    NSPersistentStoreCoordinator * psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    if (!psc)
        NSLog(@"PERSISTENT STORE COORDINATOR NOT CREATED");

    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [moc setPersistentStoreCoordinator:psc];
    self.managedObjectContext = moc;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
       NSArray *directory = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                               inDomains:NSUserDomainMask];
        NSURL *storeUrl = [directory lastObject];
        storeUrl = [storeUrl URLByAppendingPathComponent:@"Favorites.sqlite"];

        NSError *error = nil;
        NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType
                                                     configuration:nil
                                                               URL:storeUrl
                                                           options:nil
                                                             error:&error];
        if (!store)
        {
            NSLog(@"ERROR CREATING STORE: %@ %@", error.localizedDescription, error.domain);
            // present error to user
        }
        else
        {
            dispatch_sync(dispatch_get_main_queue(), ^{
                // do something once the stack is finished being created
                NSLog(@"persistent store created");
            });
        }
    });
}

You have to save core data explicitly, otherwise it won't persist. 您必须明确保存核心数据,否则它将不会持久保存。 Not hard to solve, though. 不过,这并不难解决。

In your controller implementation file (eg coreDataViewController.m), call this function when you want to save changes to core data 在控制器实现文件(例如coreDataViewController.m)中,要保存对核心数据的更改时调用此函数

// add this call, whenever you want to save data
// e.g. responding to a UIButton event
[self saveCoreDataContext];

- (void)saveCoreDataContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

My personal experience is that, even if you called [moc save:error], you may not find the content saved while you are running the app from Xcode -> Build and Run on device. 我的个人经验是,即使您调用了[moc save:error],在从Xcode->构建并在设备上运行应用程序时,也可能找不到保存的内容。 However, if you stop the Xcode from running the app, and launch the app from the device by clicking the App Icon, the content is actually persisted. 但是,如果停止Xcode运行该应用程序,然后通过单击“应用程序图标”从设备启动该应用程序,则该内容实际上将保留下来。

Just personal experience that I found through trial and error, hope that you see the same thing. 只是我通过反复试验发现的个人经验,希望您能看到同样的事情。

You have to save the MOC. 您必须保存MOC。
[mom save:nil]; [mom save:nil];

There's a few things here that stand out to me as odd. 这里有些事情对我来说很奇怪。 First, why are you threading the creation of the NSPersistentStore ? 首先,为什么要穿线创建NSPersistentStore Generally, I create the NSPersistentStoreCoordinator , add NSPersistentStore s, and then create the contexts. 通常,我创建NSPersistentStoreCoordinator ,添加NSPersistentStore ,然后创建上下文。 I would suggest doing it in that order unless you have a good reason to do otherwise. 除非您有充分的理由,否则我建议您以该顺序进行。 While it's not specifically prohibited, you may experience problems adding a NSPersistentStore after the NSManagedObjectContext has been created. 尽管没有特别禁止,但是在创建NSManagedObjectContext之后,添加NSPersistentStore可能会遇到问题。

I'm not sure if it is required or not, but I've always explicitly held a strong reference to the NSPersistentStoreCoordinator . 我不确定是否需要它,但是我一直明确地强烈引用NSPersistentStoreCoordinator It's useful to create multiple contexts, as well. 同样,创建多个上下文也很有用。 I would suggest doing so in your code. 我建议在您的代码中这样做。

As everyone else has said, you also need to explicitly save. 正如其他所有人所说,您还需要显式保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM