Core-Data中的自定义setter方法 [英] Custom setter methods in Core-Data

查看:118
本文介绍了Core-Data中的自定义setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的 NSManagedObject 子类中为一个字段编写一个自定义的setter方法(我们称为 foo $ c>。 foo 在数据模型中定义,Xcode自动生成 @property @dynamic .h和.m文件中的字段。



如果我这样写我的安装程序:

   - (void)setFoo:(NSObject *)inFoo {
[super setFoo:inFoo];
[self updateStuff];
}

然后我得到一个编译器警告调用



或者,如果我这样做:

   - (void)setFoo:(NSObject *)inFoo {
[super setValue:inFoo forKey:inFoo]
[self updateStuff];
}

然后我结束无限循环。

$ b $

解决方案

因此,为NSManagedObject的子类编写自定义setter的正确方法是什么?到文档,它将是:

   - (void)setFoo:(NSObject *)inFoo {
[self willChangeValueForKey:@foo];
[self setPrimitiveValue:inFoo forKey:@foo];
[self didChangeValueForKey:@foo];
}

这当然是忽略了 NSManagedObjects 只需要 NSNumbers NSDates NSDatas NSStrings 作为属性。



然而,这可能不是最好的方法。因为当你的 foo 属性的值改变时,你想要的东西发生,为什么不用键值观察?在这种情况下,它听起来像是KVO的方式去。


I need to write a custom setter method for a field (we'll call it foo) in my subclass of NSManagedObject. foo is defined in the data model and Xcode has autogenerated @property and @dynamic fields in the .h and .m files respectively.

If I write my setter like this:

- (void)setFoo: (NSObject *)inFoo {
    [super setFoo: inFoo];
    [self updateStuff];
}

then I get a compiler warning on the call to super.

Alternatively, if I do this:

- (void)setFoo: (NSObject *)inFoo {
    [super setValue: inFoo forKey: inFoo];
    [self updateStuff];
}

then I end up in an infinite loop.

So what's the correct approach to write a custom setter for a subclass of NSManagedObject?

解决方案

According to the documentation, it'd be:

- (void) setFoo:(NSObject *)inFoo {
  [self willChangeValueForKey:@"foo"];
  [self setPrimitiveValue:inFoo forKey:@"foo"];
  [self didChangeValueForKey:@"foo"];
}

This is, of course, ignoring the fact that NSManagedObjects only want NSNumbers, NSDates, NSDatas, and NSStrings as attributes.

However, this might not be the best approach. Since you want something to happen when the value of your foo property changes, why not just observe it with Key Value Observing? In this case, it sounds like "KVO's the way to go".

这篇关于Core-Data中的自定义setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆