2009-11-05 144 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」]