刷新 NSManagedObjectContext [英] Refresh NSManagedObjectContext

查看:20
本文介绍了刷新 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 的通知,并在 iPhone 应用程序中使用 mergeChangesFromContextDidSaveNotification,但它不起作用因为 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
  • 使用[NSManagedObjectContext existingObjectWithID:]获取对象ID对应的托管对象.
  • 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.

这篇关于刷新 NSManagedObjectContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆