View based NSTableView EXC_BAD_ACCESS on Lion with

2019-04-09 13:09发布

问题:

This is weird. I've got a super simple project to learn NSTableView, and it's set up in my nib, set as a View-based tableView. I've also set the dataSource and delegate to my controller obejct.

When I do this, however, and run, I get an EXC_BAD_ACCESS, with the trace starting in my main function and the rest of the stack is internal to Cocoa (so not my code).

There's really nothing fancy going on, other than this project is using ARC (it's a new project, so this was the default).

I also tried using the Analyzer to make sure I wasn't improperly doing memory managment anywhere and there were no issues with it.

I don't get the crash if I don't set the dataSource/delegate, but obviously this is not a very good way to build my app!

Any ideas?

Edit

The delegate and dataSource are both set up in IB. The code is as follows (view-based). It's important to note, I'm getting crashes whether or not this code is present, and it's the same crash in either case:

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return 5;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    NSTextField *cell = [tableView makeViewWithIdentifier:@"MyView" owner:self];

    if (nil == cell) {
        cell = [[NSTextField alloc] initWithFrame:CGRectZero];


        cell.identifier = @"MyView";
    }


    [cell setStringValue:[NSString stringWithFormat:@"Row %d", row + 1]];

    return cell;
}

回答1:

It's simple!

I had been (somewhat intentionally) trying to leak a variable (because I was too lazy to make an instance variable...writing quick code here), but of course ARC took care of that leak for me, causing the whole thing to blow up.

So, I just needed to make a strong property so the object I was trying to have stick around (which object was acting as my tableView's delegate and dataSource) would not be prematurely released.