问题
I am new to Core Data and objective-c. I am working on a project where I am taking JSON data from a web service and syncing it with core data. I successfully followed this tutorial and am able to get the JSON into core data without any problem. Where I am having trouble is updating the NSSet associated with a to-many relationship. So far I can get it to update but in doing so its creating duplicate entries in the set. For example, I tried using the Xcode generated access method in my custom ManagedObject Entity1:
Entity1<-->>Entity2<-->>Entity3
I use this code to add the Entity2 object to Entity1
NSNumber *parentIdNumber = [record valueForKey:@"parent_id"];
NSArray *parentIdArray = [NSArray arrayWithObject:parentIdNumber];
NSArray *parentEntityArray = [self managedObjectsForClass:@"Entity1" sortedByKey:@"id" usingArrayOfIds:parentIdArray inArrayOfIds:YES];
Entity1 *parentEntity = [parentEntityArray lastObject];
[parentEntity addEntity2Object:(Entity2 *)newManagedObject];
After looking at each variable at runtime, I have determined that everything is working correctly up until the last line. When I add an Entity2 to Entity1 it does in fact add the object. However, when I try and add 3 different Entity2 objects then it appears to create 3 duplicate Entity2 objects in Entity1. The 3 duplicates are of the last instance of Entity2 added.
I have also tried using the approach from this answer: https://stackoverflow.com/a/5370758/2670912. Which looks like this:
NSNumber *parentIdNumber = [record valueForKey:@"parent_id"];
NSArray *parentIdArray = [NSArray arrayWithObject:parentIdNumber];
NSArray *parentEntityArray = [self managedObjectsForClass:@"Entity1" sortedByKey:@"id" usingArrayOfIds:parentIdArray inArrayOfIds:YES];
Entity1 *parentEntity = [parentEntityArray lastObject];
NSMutableSet *entity2Set = [parentEntity mutableSetValueForKey:@"entity2"];
[entity2Set addObject:newManagedObject];
This has the same duplicate entry result except instead of getting 3 duplicate entries of the 3rd object added, I get 3 duplicate entries of the first object added.
Does anyone have any idea whats causing this?
回答1:
The snippit of code I was using turned out to be working correctly. The problem was when I was displaying the data in a UITableView
it was correctly graping the number of entities in the NSSet
thus showing the correct number of cells. However, I had an code:
NSSet *entitiesSet = [self.selectedEntity1 valueForKey:@"entity2"];
NSArray *entities = [entitiesSet allObjects];
Entity2 *entity = [entities objectAtIndex:[indexPath indexAtPosition:0]];
This cause the cell to only display the last object in the NSSet
causing it to look like duplicates. I fixed the problem by changing the 0
to a 1
like this:
Entity2 *entity = [entities objectAtIndex:[indexPath indexAtPosition:1]];
来源:https://stackoverflow.com/questions/18551842/core-data-to-many-relationship-creating-duplicates-when-adding-object-to-parent