【发布时间】:2016-03-24 17:51:20
【问题描述】:
我在核心数据实体中获取对象。然后我交叉检查一个 NSArray 并找出数据库中现有的对象是什么。 然后我将新对象插入数据库。我正在努力如何更新此代码中的现有对象。请帮助我以最好的方式做到这一点。
// get manageObjectContext
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSArray *arrIds = [arr valueForKeyPath:@"anId"];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeEntity"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"%K IN %@", @"anId", arrIds];
NSArray *existingItems = [context executeFetchRequest:fetchRequest error:&error];
//Get the existing ids:
NSArray *existingIds = [existingItems valueForKeyPath:@"anId"];
for (NSDictionary *item in arr) {
if ([existingItems containsObject:topic[@"anId"]]) {
// update exsising item
}
else{
// Insert new items done .........
}
【问题讨论】:
标签: ios objective-c core-data