3
votes

Im trying to just create a simple menu with an NSTableView using an NSarray. When i set the data source to the class i created i get EXC_BAD_ACCESS error. Wierd thing is, it worked in macruby? implementation file:

@implementation TableArray

- (id) init
{
    self = [super init];
    if(self) {
        arr = [NSArray arrayWithObjects:@"hey", @"what", @"there", nil];
    }
    return self;
}

- (NSInteger) numberOfRowsInTableView:(NSTableView *)tableView 
{
    return [arr count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn      *)aTableColumn row:(NSInteger)rowIndex
{
    return [arr objectAtIndex:rowIndex];
}

@end

Header:

@interface TableArray: NSObject <NSTableViewDataSource> {
   NSArray *arr;    
} 

- (NSInteger) numberOfRowsInTableView:(NSTableView *)tableView;
- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn  *)aTableColumn row:(NSInteger)rowIndex;
@end

And in the app delegate:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    TableArray *arr = [[TableArray alloc] init];
    [tv setDataSource:arr];
    [tv reloadData];
}

And the delegate header:

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate> {
   IBOutlet NSTableView *tv;
}

@property (assign) IBOutlet NSWindow *window;

@end
2
You haven't initialised tv, nil targered messages should be ignored. - Ramy Al Zuhouri
tv is an IBOutlet to the tableview made in interface builder. I also have ARC enabled. The program crashing is the main problem. - user1975095
Pretty sure what's happening is something like this: you instantiate a TableArray, assign it as the dataSource of tv (which is a weak property) and then after that, no strong references to arr exists so it's deallocated. Retain arr somewhere to resolve the issue. - Carl Veazey
thanks carl that worked! - user1975095

2 Answers

1
votes

I'm betting you have ARC enabled (possibly GC). NSTableView maintains a weak reference to its data source and you aren't maintaining a strong reference to same, so ARC is releasing your data source before you are done with.

Note that it is exceptionally rare to have a data source float about like this. It is almost assuredly a part of the control layer of your app since the data source is the conduit between the table and the underlying data store.

It likely works under MacRuby because the code is slightly different or because of implementation details.

0
votes

It would be useful to know where you are initializing *tv. I'm assuming you've placed it in some NIB file that gets loaded at app startup.
Then, you should put IBOutlet NSTableView *tv; in a ViewController, ideally one that subclasses UITableViewController. a tableView reference/outlet belongs there. Also, it would be easier to use the viewController itself as dataSource, and make the connection in Interface Builder.