Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

objective c - Refresh 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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...