NSTableViewにデータを表示する方法 ~ How to display the data to the NSTableView ~
JavaのSwingですらちゃんとやったことがないから、特に苦手意識がある画面周りの実装。
ここんとこ多少調べているので、書いておく。
CoreDataを使ってTableViewに表示はできたけど、線をひっぱたりで終わってイマイチピンとこなかったので、 色々見ていたらCoreDataを使わずにデータをTableViewに表示していた人がいたので 自分もやってみた。
NSTableView(View Base)にデータを表示する方法
- MainMenu.xibを選択して、Array Controllerを追加
AppDelegate.hにArray Controllerを定義
#import <Cocoa/Cocoa.h> @interface AppDelegate : NSObject <NSApplicationDelegate> @property (assign) IBOutlet NSWindow *window; @property (assign) IBOutlet NSArrayController *arrayController; @end
Array ControllerをApp DelegateにOutlet接続
- NSTableViewを追加してContent Modeを”View Based"に設定
- TableViewのTable Contentで作成したArrayControllerをBindする
表示するためのデータモデルを定義
#import <Foundation/Foundation.h> @interface ViewDataModel : NSObject @property (retain) NSMutableArray* name; @property (retain) NSString* hoge; @property (retain) NSString* fuga; @end
各テーブルのカラムに表示するデータをバインドする
テーブルに描画される時にはバインドした変数のgetterが呼ばれるっぽいから配列で定義したnameは振る舞いを実装しておく
#import "ViewDataModel.h" @implementation ViewDataModel -(NSString*)getName{ NSString *str = [NSString stringWithFormat:@"1:%@, 2:%@ ,3:%@", [self.name objectAtIndex:1], self.hoge, self.fuga]; return str; } @end
起動時に表示したいデータモデルを作成して、表示しておしまい。
#import "AppDelegate.h" #import "ViewDataModel.h" @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSMutableArray *objects = [NSMutableArray array]; for (int i = 0; i < 7; i++) { ViewDataModel *model = [[ViewDataModel alloc] init]; NSMutableArray *array = [[NSMutableArray alloc]init]; [array addObject:@"aaaaaa"]; [array addObject:@"hoge"]; [array addObject:@"fuga"]; model.name = array; model.hoge = [NSString stringWithFormat:@"hoge %@", @"hoge"]; model.fuga = [NSString stringWithFormat:@"fuga %d", i]; [objects addObject:model]; } [_arrayController setContent:objects]; }
NSTableViewのContent ModeをCell Based
にした場合は以下の参考にしたサイトを参照。
気が向いたら書いてみるけど、これ見ればわかるし、たぶん書かない。
ちなみに今回書いたView Based
にしたサイトはこのサイトが参考にしたサイトを参考にもしています。
多謝多謝