考虑提要中的字典对象与核心数据中的排序实体之间的以下关联:
Feed CoreData
---- --------
A A
B B
C C
D D
在枚举提要时,我检查了实体中A的
[stringForKey:@"name"]
是否为EqualTo A.name
。如果匹配,我将更新实体。如果不是,我将一个新实体插入CoreData。这适用于更新和插入,但不适用于删除。考虑将对象C从提要中删除:
Feed CoreData
---- --------
A A
B B
D C
D
当我在Feed中找到“D”时,它将看到CoreData中的对象“C”不匹配,并创建了一个新对象D。因此,我现在有两个问题:我有两个“D”对象,而对象“C”不会从CoreData中删除。
因此,虽然我想结束此:
Feed CoreData
---- --------
A A
B B
D D
我现在得到的是:
Feed CoreData
---- --------
A A
B B
D C
D
D
这肯定是一个常见问题,所以我想知道确定何时从Core Data中删除实体的最佳实践是什么。
最佳答案
这是我遍历项目以确定是更新,插入还是删除操作:
-(void)updateWithJSON:(id)JSON
{
//Get an array of all related managed objects
NSMutableArray *allContacts = [[NSMutableArray alloc] initWithArray:[self getAllContacts]];
//Loop through each object downloaded from the server
for (NSDictionary *objectInfo in [JSON objectForKey:@"Contacts"])
{
NSString *objectKey = [objectInfo objectForKey:@"BackendID"];
//Get the managed object for the objectKey
Contact *contact = [[allContacts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"backendID == %@", objectKey]] lastObject];
//If the object is nil, then insert the object
if (contact == nil)
{
NSLog(@"Object with key %@ is new.", objectKey);
contact = [[Contact alloc] initWithEntity:[NSEntityDescription entityForName:@"Contact" inManagedObjectContext:self.managedObjectContext] insertIntoManagedObjectContext:self.managedObjectContext];
contact.backendID = objectKey;
}
//Assign property values
contact.firstName = [objectInfo objectForKey:@"FirstName"];
contact.lastName = [objectInfo objectForKey:@"LastName"];
contact.jobTitle = [objectInfo objectForKey:@"JobTitle"];
contact.department = [objectInfo objectForKey:@"Department"];
contact.email = [objectInfo objectForKey:@"Email"];
contact.fax = [objectInfo objectForKey:@"Fax"];
contact.primaryPhone = [objectInfo objectForKey:@"PrimaryPhone"];
contact.secondaryPhone = [objectInfo objectForKey:@"SecondaryPhone"];
//Remove the object from the array of all the objects
if ([allContacts containsObject:contact])
[allContacts removeObject:contact];
}
//Delete any objects that still remain in the array (means they were deleted server-side
for (Contact *contact in allContacts) {
NSLog(@"Removing Contact with key %@", contact.backendID);
[self.managedObjectContext deleteObject:contact];
}
NSError *error = nil;
[self.managedObjectContext processPendingChanges];
[self.managedObjectContext save:&error];
if (error)
NSLog(@"Error Saving Contacts: %@", error.localizedDescription);
}
关于ios - 如果从Feed中删除对象,则从Core Data中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17156231/