项目未记录到共享分机的CoreData

问题描述:

我确实创建了分机分机。使用这个扩展我试图将新项目插入CoreData。代码如下。变量上下文文档已创建。 context.save()没有失败。使用主/主应用程序插入到CoreData可以正常工作并呈现给用户界面。项目未记录到共享分机的CoreData

另外一件事我注意到,共享扩展的所有插入都存储在别处,但不在主应用程序中。它看起来这些项目不合并到主CoreData。

为什么我的项插入到CoreData抛出Share Extension没有合并到主CoreData?

let context = CoreDataStackManager.sharedManager.persistentContainer.viewContext 
let document = SGDocument(context: context) 
document.name = "Document Name" 
do { 
    try context.save() 
} catch { 
    fatalError("Unresolved error \(error)") 
} 

PS:Here是类似的问题,但没有答案。

+0

你有没有建立一个应用程序组,以便您可以共享的应用和扩展之间的数据? –

+0

是的。我的应用和扩展程序属于同一组。 – Ramis

+0

在终止并重新启动应用程序后,您从共享扩展中所做的更改是否显示在主应用程序中? – Marco83

我找到了解决方案。

// In the extension I am setting that VC needs to be updated/refreshed. 
UserDefaults.group.set(true, forKey: .udRefreshDocumentsVC) 

// In the view controller adding listener for application will enter foreground. 
NotificationCenter.default.addObserver(forName: .UIApplicationWillEnterForeground, object: nil, queue: nil, using: applicationWillEnterForeground) 

// In the applicationWillEnterForeground method do reload. 
    func applicationWillEnterForeground(notification: Notification) { 
     if UserDefaults.group.bool(forKey: .udRefreshDocumentsVC) { 
      _fetchedResultsController = nil 
      tableView.reloadData() 
      UserDefaults.group.set(false, forKey: .udRefreshDocumentsVC) 
     } 
    }