1

我有两个实体。(交易,客户)交易和客户具有 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;
}
4

2 回答 2

2

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

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

于 2013-05-03T07:42:45.113 回答
2

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

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

CoreData 希望保持 1:1 约束,其中 1 笔交易始终有 1 位唯一客户,反之亦然。

改为一对多

于 2013-05-03T07:42:45.603 回答