2012-09-05 30 views
0

我的數據模型有如下關係:核心數據 - 保存關係的技巧?

[Account] -|------o< [Transaction] 

作爲實現:

// in Account.h 
@property (nonatomic, retain) NSSet *transactions; 

// in Transaction.h 
@property (nonatomic, retain) Account *account; 

現在,我已經成功地創建了一個帳戶並將其插入到核心數據。我的問題是,如何向帳戶添加起始餘額?這顯然只是賬戶上的一項交易,但在數據模型中,以下兩種方式足以實現連接(即連接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]; 
} 

回答

2

是的,如果transactionsaccount被定義爲具有相反的關係,然後

newTransaction.account = newAccount; 

自動添加到newTransactionnewAccount.transactions

您可以使用po newAccount輕鬆驗證該調試器。