0

假设每个企业有很多目录,每个目录都有很多企业。

假设我有一个业务对象。该业务对象有 10 个目录 ID。

目前我会使用代理对象。MutableSetForKey,然后删除“差异”。这很麻烦。

-(void)saveManytoManyRelationship:(NSString *) relationshipInDict andRelationshipInCoreData:(NSString*) relationshipInCoreData withTable: (NSString*) table andAttribute: (NSString*) attribute andDict: (NSDictionary *) dict andDictToSave: (NSDictionary *) dictToSave forBiz: (Business* ) BusinessToSave
{
    if([dict[relationshipInDict] isNotEmpty] && [dict[relationshipInDict][0] class]!=[NSNull class]){
        NSMutableArray * DownloadedRelationship =dict[relationshipInDict];
        NSMutableSet * ObjectsReturned=[NSMutableSet set];
        for(int i=0;i<[DownloadedRelationship count];i++){
            //NSDictionary * dictOfTag=;
            NSString * Value=DownloadedRelationship[i];
            NSManagedObject * thisTag= [self lookUpFromDictToSave:table withAttribute:attribute withValue:Value withDataCache:dictToSave];
            [ObjectsReturned addObject:thisTag];
        }
        NSMutableSet * manyManagedObjects = [BusinessToSave mutableSetValueForKey:relationshipInCoreData];
        //PO1(TagsReturn);
        [self removeDifferenceBetween2MutableManagedObjectSets:manyManagedObjects withDownloadedVersion:ObjectsReturned];
    }
}

-(void) removeDifferenceBetween2MutableManagedObjectSets:(NSMutableSet *) original withDownloadedVersion:(NSMutableSet *) downloaded {
    for (NSManagedObject * someObject in downloaded)
    {
        if ([downloaded containsObject:someObject] && ! [original containsObject:someObject])
        {
            [original addObject:someObject];
        }
        else if (![downloaded containsObject:someObject] && [original containsObject:someObject])
        {
            [original removeObject:someObject];
        }
        else
        {
        }
    }
}

有没有更直接的方法来做到这一点?

4

1 回答 1

2

使用 Core Data 自动生成的方法非常容易(当你让 Xcode 创建你的 NSManagedObject 子类时)。

for (Catalog *catalog in catalogsToBeAdded) {
  [business addCatalogObject:catalog];
}

或者更简单:

[business addCatalogObjects:catalogsToBeAdded];

不需要插入逆关系。这是自动发生的。

此外,您不必担心重复数据删除。多对多关系属于类型NSSet,因此根据定义没有重复。如果两次添加相同的对象,第二次将没有任何效果。

于 2013-11-06T18:44:20.657 回答