0

我有一个 NSOutlineTableView 显示分层 HTML 数据,从 HTML 解析器加载(每个 HTML 标记是一个具有属性的对象和一个它的子元素数组)。由于某种原因,此代码在运行完所有对象后崩溃。也就是说,我看到 HTML 中所有对象的 NSLog() 结果,但之后代码崩溃:

- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item{

    if (item==nil) {
        item=rootNode;
    }
    NSLog(@"looking for child %d of element %@",index, item);
    return [[item children] objectAtIndex:index];

}


- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item{

    if (item==nil) {
        item=rootNode;
    }
    NSLog(@"Element %@ has %i children", item, [[item children] count]);
    return [[item children ]count];

}


- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item{

    NSLog(@"is item %@ with %@ children expandable?",item,[item children]);
    return [[item children] count]>0;

}


- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item{

    if (![item isKindOfClass:[HTMLNode class]]) {   //////CRASH ON THIS LINE (or at least in this function)
        return @"";
    }

    NSLog(@"Object value for: %@",item);

    return [NSString stringWithFormat:@"%@",[item description]];

}

这是一个运行示例: HTML 内容: @"<ul></ul><span class='spantext1'></span><span class='spantext2'></span>";

输出:

Element <HTMLNode: 0x7fb9234462a0> body has 3 children

looking for child 0 of element <HTMLNode: 0x7fb9234462a0> body

is item <HTMLNode: 0x7fb923437d40> ul with (
) children expandable?

Object value for: <HTMLNode: 0x7fb923437d40> ul

looking for child 1 of element <HTMLNode: 0x7fb9234462a0> body

is item <HTMLNode: 0x7fb9249255c0> span with (
) children expandable?

Object value for: <HTMLNode: 0x7fb9249255c0> span

looking for child 2 of element <HTMLNode: 0x7fb9234462a0> body

is item <HTMLNode: 0x7fb92491e1d0> span with (
) children expandable?

Object value for: <HTMLNode: 0x7fb92491e1d0> span
(lldb) (crash with EXC_BAD_ACCESS)

这是调用堆栈的顶部:

objc_msgSend() selector name: isKindOfClass:
objc[23702]: garbage collection is OFF

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libobjc.A.dylib                 0x00007fff846e7110 objc_msgSend_vtable4 + 16
1   com.303DesignLabs.SiteStats     0x0000000109dd44fd -[HTMLTreeOutlineController outlineView:objectValueForTableColumn:byItem:] + 189 (HTMLTreeOutlineController.m:51)

在所有数据都运行完之后,它几乎看起来好像在尝试再次运行 objectValueForTableColumn。就像我说的那样,崩溃发生在整个对象层次结构运行之后(终端输出证明了这一点)。无论如何,在崩溃之前,tableView 会在屏幕上出现一瞬间,所有三个元素都在各自的行中。

4

1 回答 1

1

" EXC_BAD_ACCESS" 通常意味着你正在尝试访问一个 nil 对象或指针。

从我在您的代码中看到的内容来看,您似乎总是假设“ [item children]”不是零。

如果 " [item children]" 没有孩子会怎样?结果是 NULL 吗?你应该调用objectAtIndex还是count在一个 NULL 对象上?我的猜测是否定的。

如果任何给定项没有子项,您可能应该为每个函数返回一些合理的值。

于 2012-04-20T00:00:05.657 回答