iPhoneアプリの作成 2
コードの作成
Talkクラスの作成
- Xcodeの左カラムのClassesを右クリックし「追加」→「新規ファイル」をクリック。
- 新規ファイルのテンプレートを選択ウィンドウでObjective-C classを選択(Subcalss ofはNSObject)し次へボタンをクリック。
- 新規NSObject subclassウィンドウでファイル名に「Talk.m」を入力(同時に"Talk.h"も作成をチェック)。
- 完了ボタンをクリック。
- Talk.h、Talk.mファイルができる。
- 前ページで説明したTalk.h、Talk.mの内容をそれぞれのファイルに書き保存する。
HitoritterViewController.mの作成
HitoritterViewController.mに、テーブルにデータを表示する処理、つぶやきボタンの処理、メモリー管理関連のコードを書きます。
#import "HitoritterViewController.h"
@implementation HitoritterViewController
#import "HitoritterViewController.h"
#import "Talk.h"
@implementation HitoritterViewController
@synthesize talkText;
@synthesize talksTable;
@synthesize talks;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [talks count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Talks";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"MM/dd hh:mm"];
Talk *talk = [talks objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",
[dateFormat stringFromDate:talk.createdAt],
talk.text];
return cell;
}
- (IBAction)pushOnTalk:(id)sender {
Talk *talk = [[[Talk alloc] init] autorelease];
talk.createdAt = [NSDate date];
talk.text = talkText.text;
[talks addObject:talk];
talkText.text = @"";
[talkText resignFirstResponder];
[talksTable reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
talks = [[NSMutableArray alloc] init];
}
- (void)viewDidUnload {
self.talkText = nil;
self.talksTable = nil;
self.talks = nil;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[talks release];
[super dealloc];
}
@end
- tableView: numberOfRowsInSection:メソッドはテーブルに表示するデータの件数を戻します。
- tableView: cellForRowAtIndexPath:メソッドはテーブルに表示する行の内容を戻します、表示する内容はUITableViewCellクラスのインスタンスで、ここではつぶやいた文字列と日時を連結した文字列を設定しています。またテーブルビューはOSと協調してスクロールの高速化のためにキャッシュを行っています。詳しくはiPhone SDKのドキュメントなどを参照ください。
- pushOnTalk:はつぶやきボタンを押した際の処理で、以下を行っています。
- Talkクラスのインスタンスを作成
- インスタンスに現在の日時とつぶやきの文字列を代入
- インスタンスをつぶやきを保持している配列に追加
- つぶやきの入力フィールドをクリア
- キーボードを消す
- テーブルの再表示
- その他のメソッドは主にメモリー管理などを行っています。詳しくはiPhone SDKのドキュメントなどを参照ください。
実行
ここまでできたらメニューの「ビルド」→「ビルドと実行」を選択してください。コンパイルが行われエラーが無ければシュミレータ上でひとりったー ローカル版が実行できます。なお警告が出ている場合は、ほとんどがエラーですので無視せず原因を究明してください。
ローカル版が動いたら、Ruby on Rails編に進んでください。
