UITableViewをツリー上に表示する。第1回目(データソースを作成)

facebookアプリでツリー上のテーブルが使われているのを、ご存知でしょうか。こんなやつです。



今回から数回にわたって、同じようなツリー上のテーブルを作成してみたいと思います。イメージはこんな形。
ベースとするプロジェクトは、2012-08-11の記事にあるnibファイルを使わない、iPadアプリです。この記事をベースにプロジェクトを作成してください。


まずは表示するもととなる、データソースを考えます。
親のデータとして必要なものは、名前とツリーの開閉情報、ぶら下がる子供のデータです。
それらを保持できる、次のようなクラスを作ります。

#import <Foundation/Foundation.h>

@interface Animals : NSObject {
@private
    NSString* sectionName_;
    bool openFlag_;
    NSMutableArray* types_;
}
@property(strong, nonatomic) NSString* sectionName;
@property(nonatomic) bool openFlag;
@property(strong, nonatomic) NSMutableArray* types;

- (id)initWithSectionName:(NSString*)sectionName
                 openFlag:(bool)openFlag
                    types:(NSMutableArray*)types;
@end

@implementation Animals
@synthesize sectionName = sectionName_;
@synthesize openFlag = openFlag_;
@synthesize types = types_;

- (id)initWithSectionName:(NSString*)sectionName
                 openFlag:(bool)openFlag
                    types:(NSMutableArray*)types {
    self = [super init];
    if (self) {
        sectionName_ = sectionName;
        openFlag_ = openFlag;
        types_ = types;
    }
    return self;
}

@end



子供として必要なものは、名前とfacebookのUIと異なりますが、セルを選択できるようにしたいと思いますので、選択状態を保持します。
次のようなクラスを作ります。

#import <Foundation/Foundation.h>

@interface CreatureType: NSObject {
@private
    NSString* typeName_;
    bool selected_;
}
@property(strong, nonatomic) NSString* typeName;
@property(nonatomic) bool selected;

- (id)initWithTypeName:(NSString*)typeName
              selected:(bool)selected;

@end


@implementation CreatureType
@synthesize typeName = typeName_;
@synthesize selected = selected_;

- (id)initWithTypeName:(NSString*)typeName
              selected:(bool)selected {
    self = [super init];
    if (self) {
        typeName_ = typeName;
        selected_ = selected;
    }
    return self;
}

@end



次にツリーの本体となる、UITableViewControllerを作成します。UITableViewControllerを基底クラスに、TreeTableViewControllerという名前でクラスを作成します。ついでにデータソースを保持する、配列もメンバ変数で定義しておきます。

#import <UIKit/UIKit.h>

@interface TreeTableViewController : UITableViewController {
@private
    // Data Source
    NSMutableArray* animals_;
}

@end



今回はここまで、次回は親子を表示するためのクラス作成を行います。