我试图使用NSarray创建一个带有NSTableView的简单菜单。当我将数据源设置为我创建的类时,我得到EXC_BAD_ACCESS错误。奇怪的是,它在macruby中有效吗? 实施文件:
@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
部首:
@interface TableArray: NSObject <NSTableViewDataSource> {
NSArray *arr;
}
- (NSInteger) numberOfRowsInTableView:(NSTableView *)tableView;
- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex;
@end
在app delegate中:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
TableArray *arr = [[TableArray alloc] init];
[tv setDataSource:arr];
[tv reloadData];
}
代表标题:
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSTableView *tv;
}
@property (assign) IBOutlet NSWindow *window;
@end
答案 0 :(得分:1)
我打赌你启用了ARC(可能是GC)。 NSTableView维护对其数据源的弱引用,并且您没有保持对它的强引用,因此ARC在您完成之前就会释放您的数据源。
请注意,让数据源像这样漂浮是非常罕见的。它几乎肯定是应用程序控制层的一部分,因为数据源是表和底层数据存储之间的管道。
它可能在MacRuby下运行,因为代码略有不同或由于实现细节。
答案 1 :(得分:0)
了解初始化* tv的位置会很有用。我假设你把它放在一个在app启动时加载的NIB文件中
然后,您应该将IBOutlet NSTableView *tv;
放在ViewController中,理想情况下是UITableViewController
的子类。 tableView参考/出口属于那里。
此外,将viewController本身用作dataSource会更容易,并在Interface Builder中进行连接。