【问题标题】:Update existing object in Core Data with reference to NSArray参考 NSArray 更新 Core Data 中的现有对象
【发布时间】: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


    【解决方案1】:

    你可以使用这个代码!!

    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];
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-21
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      相关资源
      最近更新 更多