我有两个实体。(交易,客户)交易和客户具有 1:1 的关系。所以交易有客户,客户有交易。
首先,我将 Customer 对象命名为“John”。第二,我制作了 Deal 对象并为客户设置了“John”(#1 交易)第三,我制作了另一个 Deal 对象并为客户设置了“John”(#2 交易)
当时,我发现了一些问题。即 #1 交易的客户自动设置为 nil,而 #2 交易的客户是“John”。
我该如何解决?
ps1。我从 web 服务器获取数据作为 JSON 像这样交易 = [id: .., ..., customer: { ... }]
ps2。每当从服务器接收数据时,我都会更新对象。
+ (Deal *)dealWithDealsDictionary:(NSDictionary *)dic inManagedObjectContext:(NSManagedObjectContext *)context
{
Deal *deal = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Deal"];
request.predicate = [NSPredicate predicateWithFormat:@"deal_id = %@", [dic[@"id"] description]];
// Execute the fetch
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
// Check what happened in the fetch
if (!matches || ([matches count] > 1)) { // nil means fetch failed; more than one impossible (unique!)
deal = [matches lastObject];
// handle error
} else if (![matches count]) {
deal = [NSEntityDescription insertNewObjectForEntityForName:@"Deal" inManagedObjectContext:context];
} else {
deal = [matches lastObject];
}
deal.deal_id = [dic[@"id"] description];
deal.deal_status = [dic[@"deal_status"] description];
deal.deal_stage = [dic[@"deal_stage"] description];
deal.deal_desc = [dic[@"deal_desc"] description];
deal.localized_deal_status = [dic[@"localized_deal_status"] description];
deal.localized_deal_stage = [dic[@"localized_deal_stage"] description];
if (dic[@"customer"]) {
[context performBlock:^{
deal.customer = [Customer customerWithDictionary:dic[@"customer"] inManagedObjectContext:context];
}];
}
return deal;
}