views:

38

answers:

1

I am writing a core data Cocoa application in which there are accounts and transactions (monetary). 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?

+1  A: 

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!)

Let's say you have a subclass Account of NSManagedObject for the account entity, and Transaction for the transaction entity. Call the inverse relationship to transactions as transactions.

Then, when you change the account for the transactions, the inverse relationship is automatically updated by 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. 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.

To perform the observation, you use KVO. Basically, you register the KVO by addObserver:forKeyPath:options:context: with a suitable set of options. Then, you get the change by implementing observeValueForKeyPath:ofObject:change:context:. The changes can be found in the dictionary passed to that method.

Yuji
Make sure in your `options:` setting of `-addObserver: forKeyPath: options: context:` that you specify that you want both the new and the old values to be passed in.
Marcus S. Zarra