My data model has the following relationship:
[Account] -|------o< [Transaction]
Which is implemented as:
// in Account.h
@property (nonatomic, retain) NSSet *transactions;
// in Transaction.h
@property (nonatomic, retain) Account *account;
Now, I’ve successfully created an Account and inserted it into Core Data. My question is, how do I add a starting balance to the account? It’s obviously just a Transaction on the Account, but is the following sufficient to make the connection both ways (ie connect newAccount.transactions as well as newTransaction.account) in the Data Model?
// we need to insert a new account
Account *newAccount = [NSEntityDescription insertNewObjectForEntityForName:[Account entityName] inManagedObjectContext:self.managedObjectContext];
// . . . configure newAccount
NSNumber *startingBalance = @([self.startingBalanceTextField.text floatValue]);
NSError *error;
// save the new account
[self.managedObjectContext save:&error];
if( !error )
{
Transaction *newTransaction = [NSEntityDescription insertNewObjectForEntityForName:[Transaction entityName] inManagedObjectContext:self.managedObjectContext];
// . . . configure newTransaction
// is this sufficient & proper? Will this add newTransaction to newAccount.transactions as well?
newTransaction.account = newAccount;
// save the starting balance
[self.managedObjectContext save:&error];
}
Yes, if
transactionsandaccountare defined as inverse relationships, thenautomatically adds
newTransactiontonewAccount.transactions.You can easily verify that in the debugger with
po newAccount.