【问题标题】:NSTableView bindings and tableViewSelectionDidChangeNSTableView 绑定和 tableViewSelectionDidChange
【发布时间】:2026-01-05 18:25:01
【问题描述】:

我有一个带有绑定的 NSTableView 设置,并且我已将委托+数据源设置为文件的所有者。表视图的元素不会触发委托方法。如果我在元素外部单击,即调用表格视图背景 - selectionShouldChangeInTableView

我不明白为什么不调用tableViewSelectionDidChange。说真的,为什么调试这么难?

-(void)tableViewSelectionDidChange:(NSNotification *)notification {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSTableView *tableView = [notification object];
    [[NSNotificationCenter defaultCenter] postNotificationName:TABLE_SELECTION object:tableView];

}

- (BOOL)selectionShouldChangeInTableView:(NSTableView *)tableView {
    NSLog(@"Hello there");
    return YES;
}

【问题讨论】:

  • 显示方法的实现,或者至少显示方法头。
  • 更新了问题。
  • selectionShouldChangeInTableView 是否总是返回 YES?
  • @Willeke 是的。这正是我的观点,难道没有任何响应者链的痕迹或可以遵循的事件吗?我敢打赌这不会是最后一次调试这个
  • 您是否专门将 NSTableView 的 delegate 连接连接到具有委托方法的控制器?

标签: objective-c cocoa nstableview cocoa-bindings


【解决方案1】:

如果你对选中的行感兴趣,可以使用委托方法

- (BOOL)tableView:(NSTableView *)aTableView shouldSelectRow:(NSInteger)rowIndex

但是更好的方法是在选择阵列控制器本身时添加一个观察者,您的表绑定到的阵列控制器

[myArrayController addObserver:self forKeyPath:@"selection" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

并使用以下方法监听更改:

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,
                                        id> *)change
                       context:(void *)context

别忘了在析构方法中移除观察者

-(void)dealloc 
{
    [super dealloc];
    [myArrayController removeObserver:self];
}

【讨论】: