cutmancometh
cutmancometh

Reputation: 1727

EXC_BAD_ACCESS why is my object being deallocated?

I'm trying to populate an NSOutlineView with some data. I've created a class to wrap around the data.

(I'm using ARC, and using xcode 5.0.2)

the .h file:

@interface OutlineDataSource : NSObject <NSOutlineViewDataSource>{
    NSArray *theData;
}

- (id)initWithArray:(NSArray*)array;
@end

the .m file

@implementation OutlineDataSource
- (id)initWithArray:(NSArray *)array{
    self = [super init];
    theData = array;
    return self;
}

- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item{
    return [theData objectAtIndex:index];
}

...some other mandatory methods here...

@end

Then in my awakeFromNib, inside an AppController class, I use it like so:

...
NSArray *theArray = [NSArray arrayWithObjects:@"Foo", @"Bar", nil];
OutlineDataSource *data = [[OutlineDataSource alloc]initWithArray:theArray];
[teachersSelectOutline setDataSource:data];//the name of the NSOutlineView is "teachersSelectOutline"
...

The application terminates with EXC_BAD_ACCESS (code=1, address=bla bla bla)

I turned on zombies and then profiled it and it looks like the offending line is the return statement in:

- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item{
    return [theData objectAtIndex:index];
}

The output from the profiler in zombie mode is: "An Objective-C message was sent to a deallocated 'OutlineDataSource' object (zombie) at address: bla bla bla"

and the console output if I run it with zombies on, but don't profile it is: "[OutlineDataSource outlineView:child:ofItem:]: message sent to deallocated instance 0xblablabla"

Two other relevant pieces of information:

1) If, instead of using my initWithArray method, I use a basic init method where I just initialize theData to an empty array, the error goes away and the application runs just fine.

2) If I implement all the exact same code inside the AppController class, the error also goes away, and the application runs fine.

So, clearly my OutlineSourceData data object is getting its reference count decreased to zero and being deallocated. Where is this happening, and how can I stop it?

(Or, am I missing something else?)

Thanks in advance!

Upvotes: 1

Views: 265

Answers (1)

FluffulousChimp
FluffulousChimp

Reputation: 9185

You are likely experiencing the crash because the OutlineSourceData instance is being deallocated as expected. You create the instance and assign it to your NSOutlineView but the outline view only keeps a weak reference to the data source.

According to the documentation of the setDataSource: methodd "The receiver maintains a weak reference to the data source"

Make the OutlineSourceData an ivar on your AppController class instead of local to the awakeFromNib method.

Upvotes: 2

Related Questions