刷新NSManagedObjectContext

刷新NSManagedObjectContext

问题描述:

我为iPhone应用程序编写了一个WatchKit扩展。我使用应用程序组共享核心数据。这是工作,数据是共享的。当使用watch创建一个新的 NSManagedObject 时,我发送一个通知到iPhone应用程序,一个新的对象被创建。为此,我使用 MMWormhole 。 iPhone应用程序收到 MMWormhole 通知,现在我必须做最后一步 - 刷新 NSManagedObjectContext 。我该怎么办呢?

I am writing a WatchKit extension for an iPhone application. I share Core Data using App Groups. This is working, the data is shared. When a new NSManagedObject is created using watch I send a notification to the iPhone app that a new object was created. To do that I use MMWormhole. The iPhone app receives the MMWormhole notification and now I have to do the last step - refresh NSManagedObjectContext. How can I do it?

我试图在 MMWormhole 中转发 NSManagedObjectContextDidSaveNotification >通知和使用 mergeChangesFromContextDidSaveNotification 在iPhone应用程序,但它不工作 MMWormhole 序列化通知和 NSManagedObject 不支持它。

I was trying to forward notification of NSManagedObjectContextDidSaveNotification inside MMWormhole notification and to use mergeChangesFromContextDidSaveNotification in the iPhone app, but it doesn’t work as MMWormhole serialize the notification and NSManagedObject doesn’t support it.

简单的方法就是让应用重新载入数据。重新执行任何抓取,以便您从持久存储中获取最新数据。

The simple way is just to have the app reload its data. Re-do any fetches so that you get the latest data from the persistent store.

如果要使其更复杂,请执行以下操作:

If you want to make it more sophisticated, do something like this:

在手表扩展中,对于每个新的/更改/删除的对象,

In the watch extension, for every new/changed/deleted object,


  • 调用 objectID 以获取 NSManagedObjectID

  • 将对象ID转换为字符串 URIRepresentation

  • MMWormhole 邮件中传递这些字符串

  • Call objectID to get the NSManagedObjectID
  • Convert the object ID to a string URIRepresentation
  • Pass these strings in the MMWormhole message

在应用程式中,收到讯息时,

In the app, when receiving the message,


  • 使用 [NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] 将字符串转换回 NSManagedObjectID

  • 使用
  • Use [NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] to convert the strings back to an NSManagedObjectID
  • Use [NSManagedObjectContext existingObjectWithID:] to get the managed object corresponding to the object ID.