在我的iOS应用程序中,我有一个表格视图,显示来自Core Data实体的实例。选择行后,应用程序会根据实例属性值打开视图详细信息,如果需要,用户可以更改它们。在表格视图控制器中,我使用NSManagedObject
方法传递didSelectRowAtIndexPath
:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
EditToDoViewController *detailViewController = [[EditToDoViewController alloc] initWithNibName:@"EditToDoViewController" bundle:nil];
NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
detailViewController.selectedObject = selectedObject;
//[self.navigationController pushViewController:detailViewController animated:YES];
[self presentViewController:detailViewController animated:YES completion:nil];
}
然后,在EditToDoViewController
,我使用文本字段显示实例值,如下所示:
ToDoTextField.text = [[selectedObject valueForKey:@"thingName"]description];
但我现在不知道如何实现保存方法来存储更新的ToDoTextField.text
在AddToDoViewController
实现文件中,我在保存按钮操作方法中使用以下代码,但我不想插入新对象,我想更新它。
AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
NSManagedObjectContext* context = appDelegate.managedObjectContext;
NSManagedObject *favoriteThing = [NSEntityDescription insertNewObjectForEntityForName:@"FavoriteThing" inManagedObjectContext:context];
NSString *todoText = ToDoTextField.text;
[favoriteThing setValue:todoText forKey:@"thingName"];
NSError *error;
if(![context save:&error])
{
NSLog(@"Whoopw,couldn't save:%@", [error localizedDescription]);
}
答案 0 :(得分:1)
AddToDoViewController
不一定要更新托管对象。由于EditToDoViewController
已传递托管对象,因此可在用户完成编辑时更新托管对象。
// EditToDoViewController implementation
- (IBAction)SaveButtonAction:(id)sender {
AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
NSManagedObjectContext* context = appDelegate.managedObjectContext;
[selectedObject setValue:ToDoTextField.text forKey:@"thingName"];
NSError *error;
if(! [context save:&error])
{
NSLog(@"Whoopw,couldn't save:%@", [error localizedDescription]);
}
}