我正在使用CoreData和iPhone SDK。我正在制作笔记应用程序。我有一个表格,上面有我的模型显示的注释对象。按下按钮时,我想将textview中的文本保存到正在编辑的对象中。我该怎么做呢?我一直在尝试几件事,但似乎都没有。
由于
编辑:
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();
}
上面的代码正确保存,但它将其保存为新对象。我想将它保存为我在tableView中选择的那个。
答案 0 :(得分:14)
您应该查看Core Data Programming Guide。很难从问题中确切地知道你想要什么,但基本的想法是:
-(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
编辑:如果要编辑预先存在的对象,则应从获取的结果控制器中获取对象,例如: NSManagedObject *currentObject = [fetchedResultsController objectAtIndexPath:[self.tableView indexPathForSelectedRow]]
,然后编辑该对象。我还建议使用NSManagedObject的自定义子类和属性声明,而不是使用setValue:forKey
,因为它更灵活。