如果我这样写我的二传手:- (void)setFoo: (NSObject *)inFoo {[超级 setFoo: inFoo];[自我更新的东西];}然后我在调用 super 时收到编译器警告.或者,如果我这样做:- (void)setFoo: (NSObject *)inFoo {[超级 setValue: inFoo forKey: inFoo];[自我更新的东西];}然后我就陷入了无限循环.那么为 NSManagedObject 的子类编写自定义 setter 的正确方法是什么? 解决方案 这是在 .m 文件中覆盖 NSManagedObject 属性的 Apple 方法(不破坏 KVO):@interface 事务(动态访问器)- (void)managedObjectOriginal_setDate:(NSDate *)date;@结尾@implementation 事务@动态日期;- (void)setDate:(NSDate *)date{//调用setDate的动态实现(为你调用willChange/didChange)[self managedObjectOriginal_setDate:(NSString *)date;//您的自定义代码}managedObjectOriginal_propertyName 是一个内置的 magic 方法,您只需为其添加定义即可.如本页底部所示 macOS 中核心数据的新功能10.12、iOS 10.0、tvOS 10.0 和 watchOS 3.0I need to write a custom setter method for a field (we'll call it foo) in my subclass of NSManagedObject. foo is defined in the data model and Xcode has autogenerated @property and @dynamic fields in the .h and .m files respectively.If I write my setter like this:- (void)setFoo: (NSObject *)inFoo { [super setFoo: inFoo]; [self updateStuff];}then I get a compiler warning on the call to super.Alternatively, if I do this:- (void)setFoo: (NSObject *)inFoo { [super setValue: inFoo forKey: inFoo]; [self updateStuff];}then I end up in an infinite loop.So what's the correct approach to write a custom setter for a subclass of NSManagedObject? 解决方案 Here is the Apple way for overriding NSManagedObject properties (without breaking KVO), in your .m file:@interface Transaction (DynamicAccessors)- (void)managedObjectOriginal_setDate:(NSDate *)date;@end@implementation Transaction@dynamic date;- (void)setDate:(NSDate *)date{ // invoke the dynamic implementation of setDate (calls the willChange/didChange for you) [self managedObjectOriginal_setDate:(NSString *)date; // your custom code}managedObjectOriginal_propertyName is a built-in magic method you just have to add the definition for. As seen at bottom of this page What's New in Core Data in macOS 10.12, iOS 10.0, tvOS 10.0, and watchOS 3.0 这篇关于Core-Data 中的自定义 setter 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-26 13:39