核心数据 - 保存关系的技术?

时间:2012-09-05 10:39:45

标签: iphone objective-c ios core-data relation

我的数据模型具有以下关系:

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

实现方式如下:

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

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

现在,我已经成功创建了一个帐户并将其插入到Core Data中。我的问题是,如何向帐户添加起始余额?它显然只是帐户上的一个交易,但是以下内容足以在数据模型中双向建立连接(即连接newAccount.transactionsnewTransaction.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];
}

1 个答案:

答案 0 :(得分:2)

是的,如果将transactionsaccount定义为反向关系,则

newTransaction.account = newAccount;

自动将newTransaction添加到newAccount.transactions

您可以使用po newAccount在调试器中轻松验证。