使用NSArray更新Core Data中的现有对象

时间:2015-12-18 04:25:40

标签: ios objective-c core-data

我在核心数据实体中获取了对象。然后我与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 .........
    }

1 个答案:

答案 0 :(得分:0)

你可以使用这段代码!!

AppDelegate * appDelegate =     [[UIApplication sharedApplication]委托];

NSManagedObjectContext *context =
[appDelegate managedObjectContext];

NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:@"Qr_code"
            inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred =
[NSPredicate predicateWithFormat:@"(user_ID=%@)",
 kText];
[request setPredicate:pred];
matches = nil;

NSError *error;
updatedata = [context executeFetchRequest:request
                                     error:&error];

if ([updatedata count] == 0) {

} else {
    matches=updatedata[0];

}