每当特定属性更改时,如何更新NSManagedObject? [英] How to update an NSManagedObject whenever a specific attribute is changed?

查看:52
本文介绍了每当特定属性更改时,如何更新NSManagedObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有一个核心数据对象Product。每个产品都有数量价格总计属性。从表中检索项目时,Total可以提高效率。 (我知道可能存在一种使用获取的属性来获取计算值的有效方法,但这仅是一个示例,答案不是我想要的。)

Imagine I have a Core Data object, Product. Each Product has a quantity, price, and total attribute. Total is there for efficiency when retrieving items from the table. (I understand that there may be an efficient way to get the computed value using fetched properties, but this is only an example, and that answer is not what I am looking for.)

+------+----------+-------+-------+
| Name | Quantity | Price | Total |
+------+----------+-------+-------+
| Foo  |        1 |    20 |    20 |
| Bar  |        0 |    30 |     0 |
| Baz  |        3 |     5 |    15 |
+------+----------+-------+-------+

假定产品的价格从未改变。但是,数量确实发生了变化。每当数量发生变化时,我都会收到通知,以便重新计算总计。我想尽可能避免使用KVO,因为我有一个自定义的NSManagedObject类 product ,并且我想重写其方法之一以更新价格,而不是

Assume that the price of a product never changes. However, the quantity does change. Whenever the quantity changes, I would like to be notified so that I can recompute the total. I would like to avoid using KVO if possible because I have a custom NSManagedObject class, product, and I would like to override one of its methods in order to update the price and not have to worry about registering/unregistering for notifications on its own attributes.

此方法仅应在价格更改时调用,而不是每次更改属性时都应调用此方法。对象已更改。

This method should only be called when the price is changed, not every time any of the attributes on the object has changed.

我也希望此方法在值更改时立即触发(例如,在保存上下文之前不触发),以便我可以访问保存上下文之前,新的 total 属性。

I would also like this method to be triggered right when the value is changed (e.g. not right before the context is saved), so that I can access the new total attribute before the context is saved.

我应该重写哪个方法,并且可以在产品类别上的类别?

Which method should I override and can it be done in a category on my Product class?

注意:此问题类似,但主要涉及运行多个威胁d,这可能需要更复杂的答案。我正在单线程上寻找简单的东西。

Note: this question is similar but is mainly concerned with running more than one thread, which may require more complicated answers. I am looking for something simple, on a single thread.

推荐答案

您应该为 quantity 属性:

- (void)setQuantity:(NSNumber *)quantity
{
    [self willChangeValueForKey:@"quantity"];
    [self setPrimitiveValue:quantity forKey:@"quantity"];
    [self didChangeValueForKey:@"quantity"];

    NSNumber *price = ... // compute new price
    self.price = price;
}

您可以将该代码添加到Product类的类别中不想更改Xcode生成的文件

You can add that code to a category of the Product class if you don't want to change the Xcode generated files.

这篇关于每当特定属性更改时,如何更新NSManagedObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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