2009-11-05 146 views
3

我希望编辑核心数据中的现有记录。目前,我有这样的代码,但它会创建一个新的记录(以及正确的数据插入到正确的列):NSManagedObject setValue问题(核心数据)

NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext]; 
NSManagedObject *instrument = nil; 



instrument = [NSEntityDescription insertNewObjectForEntityForName: @"Instrument" 
        inManagedObjectContext: context]; 

[instrument setValue:[NSNumber numberWithInt:quantityInStockInstruments] 
    forKey: @"quantity"]; 

结果将是这样的:

Instrument | Value | Quantity 

Violin  | £25 | 9 

      |  | 8 <<< This is the new record that is created, instead of setting the 
          quantity of violin from '9' to '8' 

我想编辑当前突出显示的行的数量列的程序(在本例中为“小提琴”行,我该怎么做?

+0

如何更新当前突出显示的行取决于表如何获取其数据。你使用的是ArrayController /绑定还是数据源? – amrox 2009-11-05 20:45:10

+0

我将表绑定到一个NSArrayController,实体是:instrument。仪器实体位于核心数据模型中。 顺便说一句,我实际上没有一个.h和.m文件对应于此NSArrayController。 – Michael 2009-11-05 21:06:39

回答

4

正如refulgentis所说,线索是以选择器的名义命名的。您正在添加一个新对象。

使用NSArrayController的selectedObjects是一种更好的方法,而不是使用表格。举个例子(这是长篇大论的清晰度和我都写过了我的头顶部):

// Get the selected objects from the NSArrayController. 
// There may be more than one object selected, so this needs to be accounted for. 
NSArray *selectedObjectsArray = [yourArrayController selectedObjects]; 

// Get the first object in the array, this is the one that will have it's values changed. 
id firstSelectedObject = [selectedObjectsArray objectAtIndex:0]; 

// Change a value in a KVC compliant way 
[firstSelectedObject setValue:newValue forKey:@"keyValueToChange"]; 

编辑的评论后加入

你有一个出口的阵列控制器并在Interface Builder中正确连接它?

无论如何,代码适用于我。这是一个example project显示它的工作。

+0

嗯,我试过了,但表中的数字不会更新, 我已经基本上放在该代码中,将其更改为适合我的程序,然后重新加载表。 – Michael 2009-11-06 18:20:04

+1

适合我。我已经添加了一个示例项目的链接,您可以下载该链接以查看您需要执行的操作。 – Abizern 2009-11-06 19:10:00

+0

非常感谢那些示例代码,它让我终于明白我做错了什么! 感谢您的帮助! – Michael 2009-11-06 22:33:40

1

请注意选择器名称:“insert New Object:inContext”。

正如amrox所说,这取决于你的模型(即核心数据)和您的控制器已连接。如果不了解更多关于代码的知识,我很难说,尤其是因为我通常更多的是关于iPhone的东西(没有绑定),但基本上你需要说[[yourDataArray objectAtIndex:[table selectedRow ]] setValue:@“whatever”forKey:@“whatever”]