0

我在InterfaceBuilder中使用NSArrayController來管理在NSTableView中顯示的對象。當我選擇一行或多行時,會調用以下代碼以刪除對象並更新選擇。如何識別具有特定索引的NSTableView中的行對象?

NSIndexSet* selectedRowIndices = [m_tableView selectedRowIndexes]; 
if (!selectedRowIndices || selectedRowIndices.count < 1) { 
    return; 
} 
[self removeObjectsAtIndices:selectedRowIndices]; 

// ------------------------------------------------------- 
// SELECT ROW BELOW OR EQUAL TO THE LAST DELETED ROW. 
// ------------------------------------------------------- 

// Retrieve the highest selection index (lowest row). 
NSInteger highestSelectedRowIndex = NSNotFound; 
for (NSUInteger index = selectedRowIndices.firstIndex; index < selectedRowIndices.count; ++index) { 
    if (index > highestSelectedRowIndex) { 
     highestSelectedRowIndex = index; 
    } 
} 
if (highestSelectedRowIndex != NSNotFound && highestSelectedRowIndex < [m_tableView numberOfRows]) { 
    // 1) Get the selected object for the highest selected index. 
    // TODO: Retrieve the object from m_tableView or m_arrayController somehow!?! 
    // 2) Update the table view selection. 
    //[self updateTableViewWithSelectedObjects:...]; 
} 

但是,我找不到如何識別與前一個選擇的最高索引相匹配的對象。
爲什麼?我想將新選擇移動到最後一個選擇下面的行。


注意:上面的代碼包含了幾種錯誤!

這就是我最終的結果 - 感謝托馬斯澄清。

NSUInteger nextSelectedRowIndex = selectedRowIndices.firstIndex; 
if (nextSelectedRowIndex != NSNotFound) { 
    if (nextSelectedRowIndex >= m_tableView.numberOfRows) { 
     nextSelectedRowIndex = m_tableView.numberOfRows - 1; 
    } 
    id nextSelection = [[m_arrayController arrangedObjects] objectAtIndex:nextSelectedRowIndex]; 
    [self updateTableViewWithSelectedObjects:nextSelection]]; 
} 

回答

3

NSIndexSet中的索引是按順序排列的。沒有必要尋找最高的循環。

如果您想要選擇給定的行,只需調用-selectRowIndexes:byExtendingSelection:與您要建立的新選擇。例如,[m_tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:highestSelectedRowIndex] byExtendingSelection:NO]。你不需要知道是哪個對象。

如果您仍想知道該對象,則必須獲取陣列控制器的arrangedObjects並將-objectAtIndex:應用於該對象。

相關問題