Objective-C:覆盖动态 getter
我有一个 NSManagedObject
子类 MyClass
,其属性 myProp
定义为 @dynamic
。我的代码中有多种通过 [myClass myProp]
读取 myProp
的实例。
现在,我想为 myProp
定义一个 getter(在附加某些内容后返回 myProp
),而不更改对 [myClass myProp] 的各种调用。即不创建一个名为 getMyProp
以外的名称的 getter。
我的问题是,如果我创建一个 getter getMyProp
,它将覆盖 NSManagedObject
创建的 getter,我如何访问存储在数据库中的原始值?
I have an NSManagedObject
subclass MyClass
with a property myProp
, which is defined @dynamic
. There are various instances of reading myProp
in my code, via [myClass myProp]
.
Now, I want to define a getter (that returns myProp
after appending something to it) for myProp
, without changing the various calls to [myClass myProp]. i.e. without creating a getter that is named something other than getMyProp
.
My question is, if I create a getter getMyProp
, which will override the getter created by NSManagedObject
, how do I access the original value that is stored in the database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要访问托管对象的基础值,可以使用以下两种方法:
- (id)primitiveValueForKey:(NSString *)key
- (void)setPrimitiveValue:(id)value forKey:(NSString *)key
这通常用于将 NSNumber 属性转换为其“真实”类型,例如 bool 属性:
willAccessValueForKey:
和didAccessValueForKey:
是底层托管对象类处理故障和关系等所需的。如果您最终编写了 setter,则还必须将访问器包装在 KVC 方法中:
话虽如此对此,我个人不建议您保留相同的方法名称,除非您有充分的理由。对于“派生”值,您通常希望创建一个具有不同名称的全新方法。在整个代码中快速查找/替换并不需要很长时间。
编辑:添加 willAccessValueForKey:/didAccessValueForKey: (感谢 jrturton)
To access the underlying values of a managed object you use the following two methods:
- (id)primitiveValueForKey:(NSString *)key
- (void)setPrimitiveValue:(id)value forKey:(NSString *)key
This is often used to convert NSNumber attributes into their 'real' type, for example a bool property:
The
willAccessValueForKey:
anddidAccessValueForKey:
are required by the underlying managed object class for handling faults and relationships etc.And if you do end up writing a setter, you must also wrap the accessor in KVC methods:
Having said this, I would personally not recommend you keep the same method name unless you have a good reason. For 'derived' values you generally want to create a brand new method with a different name. It doesn't take long to do a quick find/replace throughout your code.
EDIT: added willAccessValueForKey:/didAccessValueForKey: (thanks jrturton)