简体   繁体   English

可可粘合剂:改变后变旧

[英]Cocoa bindings: get old value upon change

I am writing a core data Cocoa application in which there are accounts and transactions (monetary). 我正在编写一个核心数据Cocoa应用程序,其中包含帐户和交易(货币)。 The account entity description contains a balance attribute. 帐户实体描述包含余额属性。 The transaction entity description has a relationship to an account. 交易实体描述与帐户有关系。

I need the application to update account balances when transactions have their accounts set or changed. 当交易设置或更改其帐户时,我需要该应用程序来更新帐户余额。 For example, if a transaction's account is changed from checking to credit, the balances of both checking and credit should be changed to reflect this. 例如,如果交易的帐户从支票更改为贷方,则支票和贷方的余额都应更改以反映这一点。

The problem I am having is that I am unsure how to determine the transaction's old account so I can update its balance. 我遇到的问题是我不确定如何确定交易的旧帐户,因此可以更新其余额。 I am using bindings. 我正在使用绑定。

Can anyone point me in the right direction? 谁能指出我正确的方向?

I assume that the account entity has the inverse relationship to the transactions. 我假设帐户实体与交易具有相反的关系。 (Apple strongly suggests you always have inverse relationships. So if you haven't, please set it up!) (Apple强烈建议您始终保持逆向关系。因此,如果没有,请进行设置!)

Let's say you have a subclass Account of NSManagedObject for the account entity, and Transaction for the transaction entity. 假设您有一个用于帐户实体的NSManagedObject子类Account ,以及用于事务实体的Transaction Call the inverse relationship to transactions as transactions . 将与事务的逆关系称为transactions

Then, when you change the account for the transactions, the inverse relationship is automatically updated by CoreData. 然后,当您更改交易帐户时,CoreData会自动更新逆向关系。 So, all you have to do is to write a self-observation routine for transactions in Account so that the Account objects keep track of the balance themselves. 因此,您要做的就是为Account transactions编写一个自我观察例程,以便Account对象自己跟踪余额。 I think it is more object-oriented-y to make Account objects to take care of themselves than changing the balance from the side of the Transaction object... although of course it depends on your taste. 我认为,使Account对象自理比从Transaction对象的侧面更改余额要更面向对象……尽管当然这取决于您的喜好。

To perform the observation, you use KVO . 要执行观察,请使用KVO Basically, you register the KVO by addObserver:forKeyPath:options:context: with a suitable set of options. 基本上,您可以通过addObserver:forKeyPath:options:context:和一组合适的选项来注册KVO。 Then, you get the change by implementing observeValueForKeyPath:ofObject:change:context: . 然后,通过实现observeValueForKeyPath:ofObject:change:context:获得更改。 The changes can be found in the dictionary passed to that method. 可以在传递给该方法的字典中找到更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM