views:

246

answers:

1

I am using CoreData with iPhone SDK. I am making a notes app. I have a table with note objects displayed from my model. When a button is pressed I want to save the text in the textview to the object being edited. How do I do this? I've been trying several things but none seem to work.

Thanks

EDIT:

NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newManagedObject setValue:detailViewController.textView.text forKey:@"noteText"];

NSError *error;
if (![context save:&error]) {
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

The above code saves it correctly but it saves it as a new object. I want it to be saved as the one I have selected in my tableView.

+2  A: 

You should check out the Core Data Programming Guide. It's hard to know exactly what you want from the question, but the basic idea is:

-(IBAction)saveNote { //hooked up in Interface Builder (or programmatically)
    self.currentNote.text = self.textField.text; //assuming currentNote is an NSManagedObject subclass with a property called text, and textField is the UITextField
}

//later, at a convenient time such as application quit
NSError *error = nil;
[self.managedObjectContext save:&error];  //saves the context to disk

EDIT: If you want to edit a preexisting object, you should get the object from the fetched results controller, e.g. NSManagedObject *currentObject = [fetchedResultsController objectAtIndexPath:[self.tableView indexPathForSelectedRow]], then edit that object. I'd also recommend using a custom subclass of NSManagedObject with property declarations, rather than using setValue:forKey, since it's more flexible.

eman
Thanks, actually just worked this out. Had to modify it a little because I'm working with the iPad but basically the same code. Thanks
John