我希望视图中的某些标签始终显示NSManagedObject属性的实际状态。
例如,我有firstNameLabel
。我用NSManagedObject.firstName
的数据填充它。 NSManagedObject
更新后如何动态更新数据?我看到了很多这样的标签。
我已经读过我需要监控NSManagedObjectContextObjectsDidChangeNotification
并查看所有更改(如果是上下文),但这只是这样做的方式,我们还有更简单的方法吗?我将如何检查更改是否在我想要的NSManagedObject中完成(例如,如果我已经更改了1000个对象,但我只需要从一个更新数据)。
答案 0 :(得分:0)
解决方案:
var yourObject: YourManagedObjectClass! // here your example object
override func viewDidLoad() {
// … your other init code
// don't forget to remove observer
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.objectContextObjectsDidChange(_:)), name: NSManagedObjectContextObjectsDidChangeNotification, object: yourObject.managedObjectContext)
}
/// Object did changed, let's look what had changed
func objectContextObjectsDidChange(notification: NSNotification) {
guard let userInfo = notification.userInfo,
let updatedObjects = userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject> where updatedObjects.count > 0 else { return }
for object in updatedObjects {
if let updatedObject = object as? YourManagedObjectClass where updatedObject.objectID == yourObject.objectID {
// Data changed in our object, you can refresh your label here
// Don't forget about threads if your object wasn't in main context
label.text = updatedObject.text
return
}
}
}