如何在
Swift中为NSManagedObject实现自定义setter.我需要在设置NSMangedObject属性之前完成任务.
解决方法
我的建议是使用KVC.也许不是最优雅的解决方案,但在概念上是KVC的逻辑应用.
观察属性的更改.注册init中的更改(entity:insertIntoManagedObjectContext :)或者在awakeFromFetch和awakeFromInsert中更好,并删除willTurnIntoFault中的观察者.
init(entity: NSEntityDescription!,insertIntoManagedObjectContext context: NSManagedObjectContext!) { super.init(entity: entity,insertIntoManagedObjectContext: context) addObserver(self,forKeyPath: "attribute",options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old,context: nil) } override func observeValueForKeyPath(keyPath: String!,ofObject object: AnyObject!,change: NSDictionary!,context: CMutableVoidPointer) { if (keyPath == "attribute") { // do what you need to do } }
针对Swift 3进行了更新:
init(entity: NSEntityDescription!,options: [.old,.new],context: nil) } override func observeValue(forKeyPath keyPath: String?,of object: Any?,change: [NSKeyValueChangeKey : Any]?,context: UnsafeMutableRawPointer?) { if keyPath == "attribute" { // do what you need to do } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。