NSTableViewにデータを表示する方法 ~ How to display the data to the NSTableView ~

JavaのSwingですらちゃんとやったことがないから、特に苦手意識がある画面周りの実装。
ここんとこ多少調べているので、書いておく。

CoreDataを使ってTableViewに表示はできたけど、線をひっぱたりで終わってイマイチピンとこなかったので、 色々見ていたらCoreDataを使わずにデータをTableViewに表示していた人がいたので 自分もやってみた。

NSTableView(View Base)にデータを表示する方法

  1. MainMenu.xibを選択して、Array Controllerを追加 f:id:katz-lifehack:20130608175710p:plain
  2. AppDelegate.hにArray Controllerを定義

     #import <Cocoa/Cocoa.h>
     @interface AppDelegate : NSObject <NSApplicationDelegate>
     @property (assign) IBOutlet NSWindow *window;
     @property (assign) IBOutlet NSArrayController *arrayController;
     @end
    
  3. Array ControllerをApp DelegateにOutlet接続 f:id:katz-lifehack:20130608175017p:plain

  4. NSTableViewを追加してContent Modeを”View Based"に設定 f:id:katz-lifehack:20130608175022p:plain
  5. TableViewのTable Contentで作成したArrayControllerをBindする f:id:katz-lifehack:20130608175001p:plain
  6. 表示するためのデータモデルを定義

     #import <Foundation/Foundation.h>
     @interface ViewDataModel : NSObject
     @property (retain) NSMutableArray* name;
     @property (retain) NSString* hoge;
     @property (retain) NSString* fuga;
     @end
    
  7. 各テーブルのカラムに表示するデータをバインドする f:id:katz-lifehack:20130608174951p:plain

  8. テーブルに描画される時にはバインドした変数の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
    
  9. 起動時に表示したいデータモデルを作成して、表示しておしまい。

     #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にしたサイトはこのサイトが参考にしたサイトを参考にもしています。
多謝多謝

参考にしたサイト

NSTableView * NSArrayController && !CoreData

ビュー・ベースのNSTableViewをさわってみたよ