使用核心数据实现枚举的最佳方式 [英] Best way to implement Enums with Core Data
问题描述
将Core Data实体绑定到枚举值的最佳方式是什么,以便能够为实体分配类型属性?换句话说,我有一个名为 Item
的实体,带有一个 itemType
属性,我想绑定到枚举,
What is the best way to bind Core Data entities to enum values so that I am able to assign a type property to the entity? In other words, I have an entity called Item
with an itemType
property that I want to be bound to an enum, what is the best way of going about this.
推荐答案
如果要限制值,您必须创建自定义访问器到枚举。因此,您首先要声明一个枚举,例如:
You'll have to create custom accessors if you want to restrict the values to an enum. So, first you'd declare an enum, like so:
typedef enum {
kPaymentFrequencyOneOff = 0,
kPaymentFrequencyYearly = 1,
kPaymentFrequencyMonthly = 2,
kPaymentFrequencyWeekly = 3
} PaymentFrequency;
然后,声明属性的getter和setter。这是一个坏主意,重写现有的,因为标准访问器期望一个NSNumber对象而不是标量类型,如果绑定或KVO系统中的任何东西尝试和访问您的值,你会遇到麻烦。
Then, declare getters and setters for your property. It's a bad idea to override the existing ones, since the standard accessors expect an NSNumber object rather than a scalar type, and you'll run into trouble if anything in the bindings or KVO systems try and access your value.
- (PaymentFrequency)itemTypeRaw {
return (PaymentFrequency)[[self itemType] intValue];
}
- (void)setItemTypeRaw:(PaymentFrequency)type {
[self setItemType:[NSNumber numberWithInt:type]];
}
最后,您应该实现 + keyPathsForValuesAffecting&
,因此当itemType更改时,您可以获取itemTypeRaw的KVO通知。
Finally, you should implement + keyPathsForValuesAffecting<Key>
so you get KVO notifications for itemTypeRaw when itemType changes.
+ (NSSet *)keyPathsForValuesAffectingItemTypeRaw {
return [NSSet setWithObject:@"itemType"];
}
这篇关于使用核心数据实现枚举的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!