4

在获取要修改的对象后,我似乎无法弄清楚如何更新核心数据对象。

这就是我想要做的:

1)从核心数据匹配谓词条件中查找第一个对象:

NSInteger storeId = 235;  //find object with this id in core data

NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:[self.managedObjectContext persistentStoreCoordinator]];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Store"
                                          inManagedObjectContext:context];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %i",storeId];
[request setPredicate:predicate];

NSArray *results = [context executeFetchRequest:request error:NULL];

2)如果找到匹配,更新匹配对象(这是我需要帮助的地方):

if (results != nil && [results count] > 0)
{
    /** Not sure how to get the correct context and modify object **/

    Store *matchingObject = [results objectAtIndex:0];
    [context setValue:[NSNumber numberWithInteger:storeId] forKey:"id"];
}


/** Save the context */
NSError *error = nil;
if (![context save:&error]) {     
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        //abort();
}

感谢您提供任何帮助...

4

1 回答 1

2

尝试直接修改对象属性并保存:

matchingObject.id = [NSNumber numberWithInteger:storeId];

该对象最初是使用 获取的,context因此您应该能够通过调用 save on 来保存您的更改context

于 2012-10-30T23:53:40.800 回答