这是网站上的首次提问者 . 我一直试图通过从故事板中取出绑定并尝试在代码中重现效果来了解更多关于与NSArrayController相关的NSTableView绑定 . 我能够使用绑定配置NSTableView和NSArrayController的初始排序顺序,但我仍然无法在单击它们时对列进行排序 .
背景是我在故事板中有一个基于单元格的标准NSTableView,它通过IBOutlet绑定到NSViewController . NSViewController具有以下viewDidLoad方法:
- (void)viewDidLoad
{
[super viewDidLoad];
//setup the array controller
self.arrayController = [NSArrayController new];
[self.arrayController addObject:@{@"namef": @"Test1", @"namel": @"a"}];
[self.arrayController addObject:@{@"namef": @"Test2", @"namel": @"b"}];
[self.arrayController addObject:@{@"namef": @"Test3", @"namel": @"c"}];
[self.arrayController addObject:@{@"namef": @"Test4", @"namel": @"B"}];
//setup the table view column bindings and sorting
[[self.tableView tableColumnWithIdentifier:@"0"] bind:NSValueBinding toObject:self.arrayController withKeyPath:@"arrangedObjects.namef" options:nil];
[[self.tableView tableColumnWithIdentifier:@"0"] setSortDescriptorPrototype:[NSSortDescriptor sortDescriptorWithKey:@"namef" ascending:YES selector:@selector(caseInsensitiveCompare:)]];
[[self.tableView tableColumnWithIdentifier:@"1"] bind:NSValueBinding toObject:self.arrayController withKeyPath:@"arrangedObjects.namel" options:nil];
[[self.tableView tableColumnWithIdentifier:@"1"] setSortDescriptorPrototype:[NSSortDescriptor sortDescriptorWithKey:@"namel" ascending:YES selector:@selector(caseInsensitiveCompare:)]];
//Bind the array controller to the tableView
[self.tableView bind:NSContentBinding toObject:self.arrayController withKeyPath:@"arrangedObjects" options:nil];
[self.tableView bind:NSSelectionIndexesBinding toObject:self.arrayController withKeyPath:@"selectionIndexes" options:nil];
//setup sorting
[self.tableView setSortDescriptors:[NSArray arrayWithObject: [[NSSortDescriptor alloc] initWithKey:@"namel" ascending:YES selector:@selector(caseInsensitiveCompare:)]]];
[self.arrayController bind:NSSortDescriptorsBinding toObject:self withKeyPath:@"sortDescriptors" options:nil];
[self.arrayController setAutomaticallyRearrangesObjects:YES];
}
这导致成功加载屏幕,表格视图按“namel”数据排序,每个列 Headers 显示为可点击,每次点击时向上/向下箭头 .
但是,排序顺序没有变化......
阅读各种其他文章和stackoverflow问题我看到的答案,如“你只需要将列绑定到数组控制器,NSTableView将自动绑定自己”以及经常涉及故事板的各种其他解释 .
我已经尝试了各种组合来评论下面代码的组件 . 我已经尝试更改每列中sortDescriptorPrototypes的文本 .
我知道我错过了一条重要的线索,关于这方面的文件很糟糕 . 谁能看到我做错了什么?如何才能正确绑定它,以便单击列 Headers 实际上对数据进行排序?
1 回答
因此,这些事情很常见,我自己找到了答案 . 所以对于那些将来的人,请阅读以下内容:
我的问题是我在NSArrayController和NSTableView之间连接了太多的绑定 . 我的问题中的绑定是:
a)2个表视图列将它们的值绑定到数组控制器的内容
b)表视图还将其内容绑定到数组控制器
c)table-view将它的选择索引绑定到array-controller
d)数组控制器将其排序描述符绑定到表视图排序描述符的本地引用 .
我删除了绑定b和c,一切都开始工作了 . 我以为我之前尝试过,但是当我尝试它时,肯定会有一个额外的错误 . 下面是我的viewDidLoad方法的功能副本: