我的魔法记录代码有问题:
Collection *collection = [Collection MR_createEntity];
[collection setValue:name forKey:@"name"];
[collection setValue:date forKey:@"date"];
[collection setValue:amount forKey:@"amount"];
for (Person *person in self.selectedPeople) {
Payment *payment = [Payment MR_createEntity];
[payment setValue:person forKey:@"person"];
[payment setValue:collection forKey:@"collection"];
}
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
if (!success)
NSLog(@"Error: %@", [error localizedDescription]);
else
NSLog(@"Item %@ added to database", collection.name);
}];
对于用户选择的每个人,我想在数据库中创建付款。我在循环中这样做。我的问题只是最后一笔付款有收藏。
例如,当我有3个人时,它看起来像是:
Payment 1 - person:John, collection: nil
Payment 2 - person:Bill, collection: nil
Payment 3 - person:Mark, collection: Paper
任何人都可以告诉我为什么会这样?
答案 0 :(得分:0)
我的猜测是,这是从收款到付款的关系。您尝试使用从收集到付款的多对一,但您可能只在Core Data模型中进行一对一设置。
我不确定从收款到付款的多对一关系是个好主意。您可能希望为每个集合创建一个唯一的实体,但这一切都取决于您的模型。
for (Person *person in self.selectedPeople) {
// Create a new collection entity for each payment.
Collection *collection = [Collection MR_createEntity];
[collection setValue:name forKey:@"name"];
[collection setValue:date forKey:@"date"];
[collection setValue:amount forKey:@"amount"];
Payment *payment = [Payment MR_createEntity];
[payment setValue:person forKey:@"person"];
[payment setValue:collection forKey:@"collection"];
}
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
if (!success)
NSLog(@"Error: %@", [error localizedDescription]);
else
NSLog(@"Item %@ added to database", collection.name);
}];