扩展 NSManagedObject 类 Objective-C 中的包装方法
我在 iOS 应用程序中使用 CoreData。除了 xcdatamodel 中被建模的布尔值和 NSNumber 标记为布尔值的字段之外,一切正常。 对于此类字段,我想在扩展类中编写一些实用方法,但我想知道编写它们的最佳位置在哪里或者最佳实践是什么。
在 MyManagedObject.h 中,我有:
@interface MyManagedObject : NSManagedObject {
@private
}
@property (nonatomic, retain) NSNumber * mandatory;
@end
其中强制的是数据模型中的布尔值。这是从 xcode 生成的类:
@implementation MyManagedObject
@dynamic mandatory;
此时,为了正确使用实体,我需要在某处编写一些实用程序包装方法,可能在实体本身中,例如:
[myManagedObject mandatoryWrapper:YES];
-(void)mandatoryWrapper:(BOOL)mandatory {
// convert boolean to number
self.mandatory=convertedMandatory;
}
但我的目标是使用原始的 getter/setter 来不生成“混乱”:
// setter
myManagedObject.mandatory=YES;
//getter
if(myManagedObject.isMandatory)
但我认为重写原始方法会在应用程序生命周期的后期引起一些问题,例如在上下文中保存或检索时。
谢谢。
I am using CoreData in an iOS application. Everything works fine except for fields marked as Boolean in xcdatamodel that get modeled and NSNumber.
For this kind of fields I want to write some utility method in extended class, but I was wondering where's the best location for writing them or what's the best practice.
In MyManagedObject.h I have:
@interface MyManagedObject : NSManagedObject {
@private
}
@property (nonatomic, retain) NSNumber * mandatory;
@end
Where mandatory is a boolean in data model. This is the generated class from xcode:
@implementation MyManagedObject
@dynamic mandatory;
At this point, for properly using the entity I need to write somewhere some utility wrapper methods, probably in the entity itself, such as:
[myManagedObject mandatoryWrapper:YES];
-(void)mandatoryWrapper:(BOOL)mandatory {
// convert boolean to number
self.mandatory=convertedMandatory;
}
But I am aiming to use the original getter/setter for not generating "confusion":
// setter
myManagedObject.mandatory=YES;
//getter
if(myManagedObject.isMandatory)
but I suppose that rewriting the original methods, will cause some problem later on in the application lifecycle, for example when saving or retrieving in context.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想要一个真正的布尔属性,那么您必须更改名称。我建议将其作为类的属性而不是实体的属性,因为实体不必了解它们。
在您的情况下,您需要类似的东西:
这可以让您使用方便的构造,例如:
Core Data 很高兴,因为实体建模的 NSNumber 属性仍然存在并且按预期工作,但人们可以使用更容易理解的布尔版本。
If you want a true boolean property, then your are forced to change the name. I would recommend just making the it a property of the class and not the entity because the entity doesn't have to know about them.
In your case, you would need something like:
This lets you use convience constructions like:
Core Data is happy because the entity modeled NSNumber property is still there and works as expected but the human can use the easier to comprehend boolean version.