-(void)passDataBack:(PersonHolder *)contact{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName == %@",contact.firstName];
[request setPredicate:predicate];
NSError *error;
Person *person = [[self.managedObjectContext executeFetchRequest:request error:&error]lastObject];
[person.firstName setValue:contact.firstName forKey:@"fistName"];
[person.lastName setValue:contact.lastName forKey:@"lastName"];
if(![self.managedObjectContext save:&error]){
NSLog(@"Could not save edited data");
}
}
在运行时我可以看到contact
加载了我正在传递的所有数据,但是我的人员实体没有得到更新。
我看到答案how to update core data entered values,我认为我肯定遗漏了一些东西
答案 0 :(得分:0)
你不会错过任何东西,恰恰相反
核心数据等同于简单属性设置器
person.firstName = contact.firstName
是
[person setValue:contact.firstName forKey:@"firstName"];
[person setValue:contact.lastName forKey:@"lastName"];
还要考虑拼写错误@"fistName"
修改:尝试使用此语法
NSArray *people = [self.managedObjectContext executeFetchRequest:request error:&error];
if (error) {
NSLog(@"%@", error);
return;
}
if (people.count) {
Person *person = [people lastObject];
person.firstName = contact.firstName;
person.lastName = contact.lastName;
if(![self.managedObjectContext save:&error]){
NSLog(@"Could not save edited data");
}
} else {
NSLog(@"result array is empty"):
}
答案 1 :(得分:0)
而不是
[person.firstName setValue:contact.firstName forKey:@"firstName"];
[person.lastName setValue:contact.lastName forKey:@"lastName"];
使用
[person setValue:contact.firstName forKey:@"firstName"];
[person setValue:contact.lastName forKey:@"lastName"];
或
person.firstName = contact.firstName;
person.lastName = contact.lastName;
编辑:盲目地将最后一个获取查询对象分配给person对象并在核心数据中设置值之前的建议,检查你的fetch查询是否返回结果。这可能会崩溃。
NSArray *persons = [[[CoreDataManager sharedManager] context] executeFetchRequest:fetchRequest error:&error];
if(persons.count > 0){
// do changes in the object
}
else{
// do what you want to do to handle this situation
}