Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/102.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用NSPersistentContainer在后台保存托管对象更改_Ios_Core Data_Nsmanagedobjectcontext_Nspersistentcontainer - Fatal编程技术网

Ios 使用NSPersistentContainer在后台保存托管对象更改

Ios 使用NSPersistentContainer在后台保存托管对象更改,ios,core-data,nsmanagedobjectcontext,nspersistentcontainer,Ios,Core Data,Nsmanagedobjectcontext,Nspersistentcontainer,我在一些地方(比如)读到,将主托管上下文作为后台管理上下文的子上下文是一种很好的做法,可以节省save()时间并提高UI响应能力 Persistent Store Coordinator ↑ Managed Object Context (for saving) <= note this ↑ Managed Object Context (main) ↑ Managed Object Context (fo

我在一些地方(比如)读到,将主托管上下文作为后台管理上下文的子上下文是一种很好的做法,可以节省save()时间并提高UI响应能力

Persistent Store Coordinator
            ↑
Managed Object Context (for saving)       <= note this
            ↑
Managed Object Context (main)
            ↑
Managed Object Context (for editing)
但有一个例外:

uncaught exception 'NSInternalInconsistencyException', reason: 'Context already has a coordinator;  cannot replace.'
我的问题是:

1) 这是否意味着,要实现上述体系结构,我不能使用NSPersistentContainer,而必须使用自己的代码设置核心数据堆栈

2) 鉴于NSPersistentContainer是新的API,我认为它必须有某种方法来实现相同的效果(在后台线程中保存托管对象更改)。我想知道是什么?我正在考虑以下方法,其中save()仅在保存上下文中调用,而不是在主上下文中调用。但它更为复杂,不像上面提到的那样自然。有没有更简单的方法

          Persistent Store Coordinator
            ↑                      ↑
    Context (main)  --merge-->  Context (saving)
            ↑
    Context (editing)
更新:再想想,这种方法不起作用,因为合并是基于通知的。如果未在主上下文中调用save(),则不会触发任何通知

嗯,我想知道是否可以创建另一个mainQueueConcurrencyType的NSManagedObjectContext,按照我最初的喜好进行设置,然后用它替换由NSPersistentContainer创建的NSManagedObjectContext


谢谢你的建议。

我想我可能会找到一个解决方案:

    persistent store coordinator
      ↑                      ↑
main context          private context (edit, fetch, etc.)
  • 所有编辑都是在私有上下文中完成的
  • 主上下文不更改托管对象,只从持久存储协调器获取更新。它通过将父对象的
    automaticallyMergesChangesFromParent
    设置为true来实现
这意味着每次在私有上下文中编辑托管对象时,都应立即调用save()调用

我认为有一种情况是,用户在调用save()调用时挂起应用程序,这可能导致主上下文更新视图,而视图已从屏幕上删除。但我认为即使没有核心数据多线程,这种情况也可能发生,所以我认为UIKit应该能够正确处理这种情况

    persistent store coordinator
      ↑                      ↑
main context          private context (edit, fetch, etc.)