I need help figuring out how to display the contents of an NSArray into a NSTableView. My NSArray is filled with (or at least I think it is) filenames from a directory. I use NSFileManager to get the names of files in a directory and then I load that info into a NSArray. But I can’t figure out how to load the NSArray into the NSTableView.
AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSTableView *tableView;
NSArray *list;
IBOutlet NSTextField *text;
NSFileManager *manager;
NSString *path;
NSString *pathFinal;
}
@property (assign) IBOutlet NSWindow *window;
- (IBAction)listArray:(id)sender;
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
return [list count];
}
- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
row:(int)row
{
return [list objectAtIndex:row];
}
- (IBAction)listArray:(id)sender {
path = @"~/Library/Application Support/minecraft/bin/";
pathFinal = [path stringByExpandingTildeInPath];
list = [manager directoryContentsAtPath:pathFinal];
[tableView reloadData];
}
- (void)dealloc
{
[super dealloc];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
}
@end
There are two ways to do this: Cocoa Bindings using
NSArrayControlleror by implementing theNSTableDataSourceprotocol in an object and assigning that object as the table view’sdatasource.It looks like you have already half-implemented the
NSTableViewDataSourcemethod. You need to add the protocol declaration to your interface to indicate that yourAppDelegateobject implements the protocol:You have already implemented the required datasource methods, so in theory everything should be working, but you possibly have not set your
AppDelegateobject as the table view’sdatasource. You can do this in code:Alternatively, you can assign the datasource in Interface Builder by setting the table view’s
datasourceoutlet to yourAppDelegateinstance.However, the main problem you have is that you are assigning an autoreleased object to your
listivar, and it is being released before the table view reloads.Your
listArraymethod is problematic. There is no reason forpathandpathFinalto be instance variables. They are only used once, so should be locally scoped. In fact, sincepathis a constant, it should be declared separately:A much better way to do this would be to declare
listas a property and synthesize its accessors:.h:
.m:
You can then use the property and it handles the retain/release for you: