没有文档或示例代码解释我们是否可以与应用扩展共享 viewContext。
AFAK,应用程序和扩展程序在不同的进程中运行,我们不应该与另一个进程/线程共享 moc。我不应该与应用扩展共享包含应用的 viewContext。
那么我们应该创建另一个 viewContext 以在应用程序扩展中使用(?但 NSPersistentContainer 只提供一个 viewContext)或在应用程序扩展中使用背景上下文(???)
While an extension is running, it communicates directly only with the host app. There is no direct communication between a running extension and its containing app; typically, the containing app isn’t even running while its extension is running. In addition, the containing app and the host app don’t communicate at all.
因此,由于它们都在不同的进程中运行,所以也许(???)我可以得出结论,当应用程序扩展请求 viewContext 时,以及当包含应用程序请求 viewContext 时,2 个 viewContext(s ) 实际上是不同的实例?
class Master {
static let shared: Master = Master()
lazy var persistentContainer: CCPersistentContainer = {
let container = CCPersistentContainer(name: "xt")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
private var _backgroundContext: NSManagedObjectContext!
var backgroundContext: NSManagedObjectContext {
if _backgroundContext == nil {
_backgroundContext = persistentContainer.newBackgroundContext()
}
return _backgroundContext
}
var viewContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
---- 更多关于如何跨进程同步数据 ----
<强>1。 WWDC 15:224_hd_app_extension_best_practices
本次 WWDC session 讨论了如何发布通知 x 进程。
<强>2。 NSMergePolicy
一个策略对象,用于解决托管对象的持久存储和内存版本之间的冲突。
<强>3。 WWDC 17:210_hd_whats_new_in_core_data
<强>4。 UserDefaults(suiteName: AppGroups.primary)!
最佳答案
您不能在应用程序和扩展程序之间共享 viewContext
。我不是说你不应该,我的意思是实际上,即使你想这样做,也根本不可能。应用程序及其扩展是两个独立的进程。 viewContext
对象由进程在运行时创建。应用程序无法将内存中的变量移交给 iOS 上的不同进程,因此不可能在两者中使用相同的实例。您还有两个不同的持久容器对象,同样是因为它们是在应用程序或扩展程序运行时创建的。
这两个容器或 View 上下文很可能使用相同的持久存储文件。这并不罕见,它允许应用程序和扩展程序访问相同的数据。
关于ios - 关于与主应用程序共享核心数据上下文的应用程序扩展编程指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45238816/