Refresh NSManagedObjectContext

只谈情不闲聊 提交于 2019-11-30 18:25:12

问题


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?

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.


回答1:


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,

  • 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,

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

Now you know which objects need refreshing.



来源:https://stackoverflow.com/questions/29563667/refresh-nsmanagedobjectcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!