2011-03-03 28 views
0

好的,所以我正在使用Core Data構建Mac OS X應用程序。修改從NSArrayController獲取的託管對象

基本佈局是有一個主窗口,其中包含一個NSTableView,該窗口顯示應用程序管理的所有對象的簡要說明;實體很簡單,包含幾個字段,如標題,日期和筆記。主窗口提供添加,刪除和修改條目的命令。添加或修改條目時,應用程序將顯示一個新窗口,該窗口可以編輯該對象的所有屬性。

編輯器窗口位於其自己的.nib中,由NSWindowController的子類進行管理,並通過調用[[SUBCLASS alloc] initWithWindowNibName:]加載。此窗口中的可編輯字段綁定到一個NSObjectController,它將管理列表中的單個條目。這個控制器沒有綁定任何超出筆尖的東西;當此控制器加載時,其和content值分別設置爲主要對象上下文和正在編輯的實體。

因此,添加對象的偉大工程,其作用如下:

NSEntityDescription *entityDesc = [[self.managedObjectModel entitiesByName] objectForKey: @"LogEntryEntity"]; 
LogEntryEntity *entry = (LogEntryEntity *) [[NSManagedObject alloc] initWithEntity: entityDesc 
    insertIntoManagedObjectContext: self.managedObjectContext]; 
LogEditorController *editor = [[LogEditorController alloc] initWithWindowNibName: @"LogEditorWindow" 
    logEntry: entry]; 
entry.date = [NSDate dateOneHourAgoTo30Minutes]; 
[editor setSaveHandler: ^(LogEditorController *c) 
{ 
    NSError *error = nil; 
    if (![self.managedObjectContext save: &error]) 
     NSLog(@"Failed to save object: %@", error); 
    [self.logTableView reloadData]; 
}]; 
[entry release]; 
[editor loadWindow]; 
[editor showWindow: self]; 

刪除的作品,太:

NSIndexSet *selectedIndexes = [self.logTableView selectedRowIndexes]; 
if ([selectedIndexes count] == 0) 
    return; 
[self.logArrayController removeObjectsAtArrangedObjectIndexes: selectedIndexes]; 
if (![self.managedObjectContext save: &error]) 
    NSLog(@"error saving: %@", error); 

但是,當我去編輯選擇的條目:

NSIndexSet *selectedIndexes = [self.logTableView selectedRowIndexes]; 
if ([selectedIndexes count] != 1) 
    return; 

LogEntryEntity *entry = (LogEntryEntity *) [[self.logArrayController arrangedObjects] objectAtIndex: [selectedIndexes firstIndex]]; 
LogEditorController *editor = [[LogEditorController alloc] initWithWindowNibName: @"LogEditorWindow" 
    logEntry: entry]; 
[editor setSaveHandler: ^(LogEditorController *c) 
{ 
    NSError *error = nil; 
    if (![self.managedObjectContext save: &error]) 
     NSLog(@"error saving: %@", error); 
}]; 
[editor loadWindow]; 
[editor showWindow: self]; 

但是,這裏發生的情況是,當窗口出現時,字段會填寫正確條目的內容。 但是,緊接着,所有的字段被設置爲某些其他條目的值(可能不是巧合,它被設置爲具有所有對象中最小對象ID的那個),並且我可以確認當窗口關閉時NSObjectControllercontent值已更改爲該不同的實體。當我第一次設置content時,我確認它是我想要編輯的那個。

這是怎麼回事?我的意思是,很明顯,我做錯了什麼,但我無法弄清楚什麼。

回答

0

我沒有看到這個代碼如何editor窗口可以切換LogEntryEntity對象,除非你有其他的代碼或不正確的綁定編輯窗口。您傳遞的是特定對象而不是對象數組,因此editor窗口如何發現其他對象錯誤地顯示?

我建議您移除此行投:

LogEntryEntity *entry = (LogEntryEntity *) [[self.logArrayController arrangedObjects] objectAtIndex: [selectedIndexes firstIndex]]; 

...因爲如果由於某種原因,從數組返回的對象是不實際的一個LogEntryEntity對象,你永遠不會知道。它可能是另一個managedObject或其他東西。在Objective-C中投射非常強大,編譯器當然會隱式地信任它們。

相關問題