在 CoreData 中保存对象

Posted

技术标签:

【中文标题】在 CoreData 中保存对象【英文标题】:Save object in CoreData 【发布时间】:2010-03-27 20:19:36 【问题描述】:

我在 iPhone SDK 中使用 CoreData。我正在制作一个笔记应用程序。我有一个表格,其中包含从我的模型中显示的注释对象。当按下按钮时,我想将 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 中选择的那个。

【问题讨论】:

【参考方案1】:

您应该查看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,因为它更灵活。

【讨论】:

谢谢,实际上刚刚解决了这个问题。不得不稍作修改,因为我正在使用 iPad,但代码基本相同。谢谢

以上是关于在 CoreData 中保存对象的主要内容,如果未能解决你的问题,请参考以下文章

以一个名称将多个对象保存到 coredata

如何以一个名称将多个对象保存到 CoreData

尝试在块中保存对象时崩溃。 (CoreData 无法满足...的错误)

CoreData 对象未在屏幕之间保存

IOS中CoreData浅析

在 coredata 中保存实体数组