Coredata关系自动设置为nil



我有两个实体。(协议、客户)交易和客户是1:1的关系。所以Deal有customer, customer有Deal。

首先,我创建了一个名为"John"的Customer对象。其次,我创建了交易对象,并将客户设置为"John"(#1交易)。第三,我创建了另一个Deal对象,并设置customer为"John"(#2 Deal)

那时候,我发现了一些问题。即#1交易的客户自动设置为nil, #2交易的客户为"John"。

我如何解决这个问题?

ps1。我从web服务器获得了像这样的JSON数据交易= [id: ..],……,顾客:{…}]

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;
}

你没有1:1的关系:它是1:N

2笔交易有相同的客户,所以1个客户有N笔交易。

CoreData希望保持1:1的约束,即一个交易总是有一个唯一的客户,反之亦然。

改为一对多

如果您希望一个客户有许多交易和/或多个客户每个有许多交易(其中每个客户可以有相同的交易),则将关系设为1对多或多对多。

引用被设置为nil,因为您说一次只能有一个引用

最新更新