使用 XCode 并打开“plist”文件时,您会在漂亮的大纲视图中获得内容。
在我的项目CoreDataUtility中,我想做一些非常类似的事情。在核心数据中,开发人员可以将 NSDictionary 和 NSArray 存储为可转换对象。我希望能够在一个漂亮的树视图中呈现这些对象,而不是仅仅将描述转储到 NSTextView 中。
我确信我可以开始编码并让它工作,但首先我想检查是否有人知道如何让 NSTreeView 本质上执行此操作,或者是否有人拥有已经执行类似操作的示例代码?
感谢您提供的任何帮助。
下面的示例不使用绑定,但应该有所帮助:https://developer.apple.com/library/mac/samplecode/SidebarDemo/Introduction/Intro.html
我认为,上面的示例比使用绑定更容易实现(即使有更多的代码)。
您不能将嵌套的
NSDictionary
对象目录与 NSTreeController
一起使用,因为字典的子级不会采用正确的形式,因为您始终需要同名的 keyPaths 来表示要在 NSOutlineView
中显示的值的专栏。
但是,您可以轻松地将嵌套的
NSDictionary
对象转换为满足此要求的稍微不同的表示形式。
假设您有一个包含两列的大纲视图。您可以将第一列的值绑定到树控制器的
arrangedObjects.col1
,将第二列的值绑定到 arrangedObjects.col2
。
然后这是创建合适的代码
NSDictionary
:
- (NSDictionary*) makeNodeFrom:(NSObject*)value withName:(NSString*)name {
NSMutableDictionary *result = NSMutableDictionary.dictionary; // has keys: name, value, children, isLeaf, count
result[@"col1"] = name;
if ([value isKindOfClass:NSDictionary.class]) {
NSMutableArray *children = NSMutableArray.array;
[(NSDictionary*)value enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSObject *obj, BOOL *stop) {
[children addObject:[self makeNodeFrom:obj withName:key]];
}];
result[@"children"] = children;
result[@"count"] = @(children.count);
} else {
result[@"isLeaf"] = @YES;
result[@"col2"] = value;
}
return result;
}
// return the model from a generic dictionary:
- (NSDictionary)myModel {
NSDictionary *sampleDict = @{
@"key1": @"value1,
@"node": @{
@"key2": @"value2"
}
};
return [self makeNodeFrom:sampleDict withName:@"root"];
}
在 Tree Controller 中,将其 Content Array 绑定到
myModel
,并设置其 keyPath 属性如下:
children
count
isLeaf