cocoa - 加载的 NSNib 对顶级对象进行排序,没有特定的顺序

标签 cocoa nstableview nib

这是我用来用数据填充基于 View 的 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对于两个连续的委托(delegate)调用,语句打印如下数组:

(
    "<MyCustomCellView: 0x7fb2abe81f70>",
    "<NSApplication: 0x7fb2ab80cbf0>"
)
(
    "<NSApplication: 0x7fb2ab80cbf0>",
    "<MyCustomCellView: 0x7fb2abb2c760>"
)

这只是几百行中的两行的输出,所以我随机地要么正确显示我的 View ,要么得到 unrecognized selector调用 setIdentifier: 时出错对于 view对象时 viewobjectAtIndex:0实际上是 NSApplication 的一个实例来自加载的 Nib 的顶级对象。

这是 Nib 加载机制中的错误还是我在这段代码中做错了什么?

最佳答案

该线程有点旧,但就其值(value)而言:

尚不清楚这是否是一个错误,因为文档没有具体说明在 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];

关于cocoa - 加载的 NSNib 对顶级对象进行排序,没有特定的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9341337/

相关文章:

objective-c - 如何在 XCode 中将自定义 UIButton 添加到 nib 文件?

cocoa - 在核心数据中建模关联类的最佳方法是什么?

objective-c - 任何一对多对多谓词

objective-c - 将焦点移至 NSTableView 中新添加的记录

macos - NSOutlineView 编译错误 : Semantic Issue 'moveRowAtIndex:toIndex:' is unavailable

iphone - 我可以在 nib 中和以编程方式定义 UIView 吗?

xcode - 如何设置 NSFontPanel 的默认值?

cocoa - CLLocationManager 不适用于非无线连接?

objective-c - 如何使用 Binding 创建带有自定义单元格的 NSTableview

macos - 10.11 NSCollectionView : "could not load the nibName: NSCollectionViewItem in bundle NSBundle"