【发布时间】:2014-02-02 20:47:04
【问题描述】:
我有一个使用 CoreData 的项目。我使用 Mogenerator 生成子类。
当我设置一个属性的值时,这个值实际上并没有被赋值。以后每次我尝试设置该值时,我之前设置的值都没有被赋值。
这很好用,因为我的底层数据框架是 Mantle,但是自从迁移到 CoreData 后,它就停止了工作。我依靠 KVO 使一些 UIView 对象与模型保持同步。
同样,CoreData NSManagedObject 子类的 ivars 似乎没有采用我分配给它们的值。
考虑如下界面:
@interface Light : _Light{}
/**
Light / Color Properties
*/
@property (nonatomic, assign) CGFloat brightness; // 0...1
@property (nonatomic, assign) CGFloat hue; // 0...1
@property (nonatomic, assign) CGFloat saturation; // 0...1
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
@property (nonatomic, readonly) UIColor *color; // derived from the above
- (void)setHue:(CGFloat)hue saturation:(CGFloat)saturation; // it often makes sense to set these together to generate fewer KVO on the color property.
@end
以及以下 .m 文件:
@interface Light ()
{
CGFloat _hue, _saturation, _brightness;
UIColor *_color;
}
@property (nonatomic, assign) BOOL suppressColorKVO;
@property (nonatomic, readwrite) UIColor *color;
@end
@implementation Light
@synthesize suppressColorKVO = _suppressColorKVO;
- (void)setHue:(CGFloat)hue saturation:(CGFloat)saturation
{
BOOL dirty = NO;
if (saturation != _saturation) {
// clamp its value
[self willChangeValueForKey:@"saturation"];
_saturation = MIN(MAX(saturation, 0.0f), 1.0f);
[self didChangeValueForKey:@"saturation"];
dirty = YES;
}
if (hue != _hue) {
[self willChangeValueForKey:@"hue"];
_hue = MIN(MAX(hue, 0.0f), 1.0f);
[self didChangeValueForKey:@"hue"];
dirty = YES;
}
if (dirty) {
if (!_suppressColorKVO) {
[self setColor: self.color];
}
}
}
// other stuff... the color accessors are also custom. Derived from the h, s, b values.
@end
我认为我对 CoreData 不满意,但我不知道出了什么问题。这些色调、饱和度、亮度都是“瞬态的”(不是核心数据意义上的),因为它们会被我们与之交互的某些硬件不断更新,因此无需保存它们的状态。
【问题讨论】:
-
'[self setColor:self.color]' 是什么意思?看起来很奇怪,你覆盖了颜色getter方法吗?
-
是的,别担心。 ;-) 两者都是自定义的,我这样做是因为颜色是派生的,而 setColor 会发送 KVO。那不是问题。它工作得很好。是 ivars 没有保持我为它们设置的值。
标签: ios objective-c core-data nsmanagedobject mogenerator