在获取我想要修改的对象后,我似乎无法弄清楚如何更新核心数据对象.
这就是我想要做的:
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();
}
感谢您提供任何帮助…
最佳答案 尝试直接修改对象属性并保存它:
matchingObject.id = [NSNumber numberWithInteger:storeId];
该对象最初是使用上下文获取的,因此您应该可以通过调用上下文保存来保存更改.