假设每个企业都有许多目录,每个目录都有很多业务。
说我有一个Business对象。该Business对象有10个catalogID。
目前我会使用代理对象。 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
{
}
}
}
有更简单的方法吗?
答案 0 :(得分:2)
通过使用Core Data自动生成的方法(当您使用Xcode创建NSManagedObject子类时)非常容易。
for (Catalog *catalog in catalogsToBeAdded) {
[business addCatalogObject:catalog];
}
甚至更简单:
[business addCatalogObjects:catalogsToBeAdded];
无需插入反向关系。这会自动发生。
此外,您不必担心重复数据删除。多对多关系的类型为NSSet
,因此根据定义,没有重复项。如果你添加两次相同的对象,第二次将没有任何效果。