Mic*_*ord 108 iphone cocoa cocoa-touch core-data objective-c
将Core Data实体绑定到枚举值的最佳方法是什么,以便我能够为实体分配类型属性?换句话说,我有一个Item
带有itemType
属性的实体,我希望将其绑定到枚举,实现此目的的最佳方法是什么.
iKe*_*dac 130
如果要将值限制为枚举,则必须创建自定义访问器.所以,首先你要声明一个枚举,如下:
typedef enum {
kPaymentFrequencyOneOff = 0,
kPaymentFrequencyYearly = 1,
kPaymentFrequencyMonthly = 2,
kPaymentFrequencyWeekly = 3
} PaymentFrequency;
Run Code Online (Sandbox Code Playgroud)
然后,为您的财产声明getter和setter.覆盖现有的是一个坏主意,因为标准访问器期望NSNumber对象而不是标量类型,如果绑定或KVO系统中的任何内容尝试访问您的值,您将遇到麻烦.
- (PaymentFrequency)itemTypeRaw {
return (PaymentFrequency)[[self itemType] intValue];
}
- (void)setItemTypeRaw:(PaymentFrequency)type {
[self setItemType:[NSNumber numberWithInt:type]];
}
Run Code Online (Sandbox Code Playgroud)
最后,您应该实现,+ keyPathsForValuesAffecting<Key>
以便在itemType更改时获取itemTypeRaw的KVO通知.
+ (NSSet *)keyPathsForValuesAffectingItemTypeRaw {
return [NSSet setWithObject:@"itemType"];
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ert 79
你可以这样做,方式更简单:
typedef enum Types_e : int16_t {
TypeA = 0,
TypeB = 1,
} Types_t;
@property (nonatomic) Types_t itemType;
Run Code Online (Sandbox Code Playgroud)
在您的模型中,设置itemType
为16位数.全部完成.无需其他代码.只需按照惯例
@dynamic itemType;
Run Code Online (Sandbox Code Playgroud)
如果您使用Xcode创建NSManagedObject
子类,请确保选中" 使用原始数据类型的标量属性 "设置.
Mik*_*lah 22
我正在考虑的另一种方法是不要声明枚举,而是在NSNumber上将值声明为类别方法.
如果您正在使用mogenerator,请查看:https://github.com/rentzsch/mogenerator/wiki/Using-enums-as-types.您可以使用名为的Integer 16属性itemType
,其attributeValueScalarType
值为Item
用户信息.然后,在实体的用户信息中,设置为定义枚举additionalHeaderFileName
的标题的名称Item
.生成头文件时,mogenerator将自动使属性具有Item
类型.
归档时间: |
|
查看次数: |
20607 次 |
最近记录: |