这是我用于使用数据填充基于视图的NSTableView的一段代码:
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
MyCustomCellView *view = (MyCustomCellView *)[tableView makeViewWithIdentifier:@"MyCustomCellView" owner:self];
if (!view) {
NSNib *cellNib = [[NSNib alloc] initWithNibNamed:@"MyCustomCellView" bundle:[NSBundle mainBundle]];
NSArray *array = nil;
if ([cellNib instantiateNibWithOwner:self topLevelObjects:&array]) {
DLog(@"%@", array);
view = [array objectAtIndex:0];
[view setIdentifier:@"MyCustomCellView"];
}
[cellNib release];
}
MyObject *object = [_objects objectAtIndex:row];
[[view titleTextField] setStringValue:object.title];
return view;
}
DLog
语句为两个连续的委托调用打印如下数组:
(
"<MyCustomCellView: 0x7fb2abe81f70>",
"<NSApplication: 0x7fb2ab80cbf0>"
)
(
"<NSApplication: 0x7fb2ab80cbf0>",
"<MyCustomCellView: 0x7fb2abb2c760>"
)
这只输出几百行中的两行,因此我随机地正确显示我的视图,或者在unrecognized selector
对setIdentifier:
对象调用view
时出现view
错误} objectAtIndex:0
实际上是来自加载的nib的NSApplication
顶级对象的实例。
这是nib加载机制中的错误还是我对此代码做错了什么?
答案 0 :(得分:5)
这个帖子有点陈旧,但值得的是:
目前尚不清楚这是否是一个错误,因为文档并未具体说明在topLevelObjects:
参数中传回的数组的顺序。但是,这段代码对我有用。
NSArray *arrayOfViews;
BOOL wasLoaded = [[NSBundle mainBundle] loadNibNamed:xibName owner:self topLevelObjects:&arrayOfViews];
NSUInteger viewIndex = [arrayOfViews indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [obj isKindOfClass:[MyCustomView class]];
}];
self = [arrayOfViews objectAtIndex:viewIndex];