Saving an updated Core Data instance [duplicate]

独自空忆成欢 提交于 2019-12-11 08:35:27

问题


In my iOS app I have a table view showing instances from a Core Data entity. After selecting a row, the app opens a view detail from the instance attributes values, and the user may change them if needed. From the table view controller I pass a NSManagedObject using the didSelectRowAtIndexPath method:

- (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];
}

Then, at the EditToDoViewController, I show the instance values using text fields, as shown below:

ToDoTextField.text = [[selectedObject valueForKey:@"thingName"]description];

But I don't know now how to implement a save method to store the updated ToDoTextField.text In the AddToDoViewController implementation file I am using following code inside a save button action method, but I dom't want to insert a new object, I want to update it.

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]);
}

回答1:


The AddToDoViewController doesn't necessarily have to update the managed object. Since the EditToDoViewController was passed the managed object, it could update the managed object when the user is finished editing.

// 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]);
    }
}


来源:https://stackoverflow.com/questions/20766823/saving-an-updated-core-data-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!