iPhone Appのサンプルコード SQLiteBooksのソースを読む - 5.「New Book」画面の表示
昨日の続きで、「New Book」画面の表示はどのように実装されているのか追ってみる。
New Book画面の表示処理
New Book画面の表示処理は AddViewControllerのスーパークラスのDetailViewControllerで実装されている。
表示項目数
表示項目は、Title、Copyright、Authorの3項目、
下記のメソッドで表示項目数を固定で返している。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tv { // 3 sections, one for each property return 3; }
入力値
ここではbookの値をcell.textに設定しているが、「+」ボタンのアクションの
MasterViewControllerのaddBookで、ここで参照されているbookを生成しているので
ここで設定される値はnullになっている。
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; if (cell == nil) { // Create a new cell. CGRectZero allows the cell to determine the appropriate size. cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"MyIdentifier"] autorelease]; } switch (indexPath.section) { case 0: cell.text = book.title; break; case 1: cell.text = [dateFormatter stringFromDate:book.copyright]; break; case 2: cell.text = book.author; break; } return cell; }
入力項目のタイトル
テキストフィールドの上に表示されるタイトルは、このメソッドで返しているようだ。
- (NSString *)tableView:(UITableView *)tv titleForHeaderInSection:(NSInteger)section { // Return the displayed title for the specified section. switch (section) { case 0: return @"Title"; case 1: return @"Copyright"; case 2: return @"Author"; } return nil; }
動きは追えてきたが、どういう仕組で動いているのか
まだよく理解できていない。
DetailViewControllerクラス
DetailViewControllerクラスの定義をみると、
この指定は何だ?
@interface DetailViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { Book *book; IBOutlet UITableView *tableView; NSDateFormatter *dateFormatter; NSIndexPath *selectedIndexPath; }
先程、New Book画面の表示処理で出て来たnumberOfSectionsInTableViewメソッドは
UITableViewDataSourceのメソッドのようだ。
UITableViewDataSourceはプロトコルだ。
Objective-CのプロトコルってJavaのインターフェースみたいなもの。
UIViewController、UITableViewDelegate、UITableViewDataSource
次は、このへんの関係をもう少し理解しよう。
プロトコルの採用
下記のようなクラスで
の部分が良くわからなかったが
Objective-C 2.0プログラミング言語 (ObjC.pdf)の
P68〜69の説明で理解できた。
@interface DetailViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { Book *book; IBOutlet UITableView *tableView; NSDateFormatter *dateFormatter; NSIndexPath *selectedIndexPath; }
の部分はプロトコルのリストで、
ここに指定したプロトコルに宣言されているメソッドをクラスで実装しなければならないようだ。