我想我已经基本了解了。记录一下,这是我必须添加到我的视图控制器的内容,这个视图控制器已经管理了一个NSOutlineView,我自己管理数据源:
创建一个树节点的类:
@interface DataNode : NSObject {}
@property (retain) NSMutableArray *children;
@property (retain) NSString *firstText;
@property (retain) NSString *secondText;
@end
@implementation DataNode
- (instancetype)init {
self.children = [NSMutableArray array];
return self;
}
- (BOOL) isLeaf {
return self.children.count == 0;
}
@end
将以下属性添加到您的视图控制器中:
@property (nonatomic, retain) NSTreeController *treeController;
@property (nonatomic, retain) NSMutableArray *treeContents;
初始化树形控制器,例如从视图控制器的awakeFromNib
方法中:
self.treeContents = [NSMutableArray array];
self.treeController = [[NSTreeController alloc] init];
[self.treeController setLeafKeyPath:@"isLeaf"];
[self.treeController setChildrenKeyPath:@"children"];
[self.treeController bind:@"contentArray" toObject:self withKeyPath:@"treeContents" options:@{NSRaisesForNotApplicableKeysBindingOption:@YES, NSConditionallySetsEditableBindingOption:@YES}];
[self.table bind:@"content" toObject:self.treeController withKeyPath:@"arrangedObjects" options:@{NSAlwaysPresentsApplicationModalAlertsBindingOption:@YES}];
[self.table bind:@"selectionIndexPaths" toObject:self.treeController withKeyPath:@"selectionIndexPaths" options:@{}];
[self.table bind:@"sortDescriptors" toObject:self.treeController withKeyPath:@"sortDescriptors" options:@{}];
将节点添加到树的根节点:
DataNode *node = [[DataNode alloc] init];
node.firstText = [NSString stringWithFormat:@"1 - %d", i1];
node.secondText = [NSString stringWithFormat:@"2 - %d", i1];
NSIndexPath *loc = [NSIndexPath indexPathWithIndex:self.contents.count];
[self.treeController insertObject:node atArrangedObjectIndexPath:loc];
由于我的NSOutlineView是基于单元格的,因此我还必须继续实现数据源方法以为单元格提供值,因为我无法找出如何进行绑定:
-(NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
return 0;
}
-(id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
return nil;
}
-(BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
return NO;
}
-(id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
DataNode *node = [item representedObject];
return [node valueForKey:tableColumn.identifier];
}
objectValueForTableColumn
方法假设表格列的标识符分别设置为 firstText
和 secondText
。