核心数据实体不更新数据

时间:2014-02-09 21:35:24

标签: ios core-data

我正在尝试使用以下代码更新核心数据实体:

(void)home:(UIBarButtonItem *)sender


{

managedObjectContext = [appDel managedObjectContext];

NSError *error;

NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Data" inManagedObjectContext:managedObjectContext];

[request setEntity:entity];
[request setPredicate:[NSPredicate predicateWithFormat:@"name=%@ and number=%@",self.name,[NSNumber numberWithInt:temp]]];


NSManagedObject *managedObject =[[NSManagedObject alloc]initWithEntity:entity insertIntoManagedObjectContext:managedObjectContext];
managedObject = [[managedObjectContext executeFetchRequest:request error:&error] lastObject];

[managedObject setValue:self.name forKey:@"name"];
[managedObject setValue:[NSNumber numberWithInt:self.number] forKey:@"number"];

[managedObjectContext save:nil];

BOOL saved = [managedObjectContext save:& error];

if (!saved)
{
    NSLog(@"Data Not Saved");
}
else
{
    NSLog(@"Data Saved");
}
[self.navigationController popToRootViewControllerAnimated:YES];

}

任何人都可以告诉我,如果我做错了什么吗?我也试过这个Solution但它没有用。

1 个答案:

答案 0 :(得分:0)

NSManagedObject *managedObject =[[NSManagedObject alloc]initWithEntity:entity insertIntoManagedObjectContext:managedObjectContext];

创建一个 new 对象。如果您想更新现有的对象,那么您应该 只执行获取请求,并更新获取的对象。

只有当没有(匹配)对象存在时,才会创建它。