我的数据模型有以下关系:
[Account] -|------o< [Transaction]
其实现为:
// in Account.h
@property (nonatomic, retain) NSSet *transactions;
// in Transaction.h
@property (nonatomic, retain) Account *account;
现在,我已经成功创建了一个 Account 并将其插入到 Core Data 中。我的问题是,如何在账户中添加起始余额?这显然只是帐户上的交易,但以下内容是否足以在数据模型中建立双向连接(即连接newAccount.transactions
和连接)?newTransaction.account
// 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];
}