2009年10月3日土曜日

CoreData のデータを UITableView で表示する

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
(前回)Cocoa Touch の日々: CoreData - テーブルの件数を取得する


件数が取得できたので今度はデータを取得し、これを UITableView へ表示する。

CoreDataからのデータ取得方法は Mac Dev Center のガイドを参考にした。
Mac Dev Center: Core Data Programming Guide: Fetching Managed Objects


データ取得ができたのでこれを UITableView へ表示する。
まず DataSource メソッドの実装。

件数は前回作成したメソッドを使用する。
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [self getCount];
}


1行毎のデータは新規に -[getEntityAtIndex:] を用意し、これを呼出す。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
NSManagedObject* managedObject = [self getEntityAtIndex:row];
cell.textLabel.text = [managedObject valueForKey:@"title"];
return cell;
}


なお UITableViewCell の textプロパティは iPhoneOS3.0よりDeprecated となっていた。その代わりに textLabelプロパティを使用する。

データ1行を取得するメソッドの実装。
- (NSManagedObject*)getEntityAtIndex:(NSUInteger)index
{
NSFetchRequest* request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Memo"
inManagedObjectContext:managedObjectContext]];
[request setIncludesSubentities:NO];

NSSortDescriptor* sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"title"
ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

NSError* error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
if (array == nil) {
NSLog(@"%@", error);
return nil;
}
return [array objectAtIndex:index];
}


毎回全件持ってくるので効率が非常に悪いがとりあえずは動く事を優先させる(この辺りは動いた後に見直そう)。

実行してみる。

出た。


※データが同じものがたくさんあるが、実際そのように入れてある。

- - - -
サンプルの動作ではなく、実際に自分で組み立ててそれが動くとうれしい。やっぱりプログラミングは楽しい。


+++++ 参考本 +++++
はじめてのiPhoneプログラミング

+++++ 関連情報 +++++
Cocoa Touch の日々: CoreDataを使う
Cocoa Touch の日々: 習作アプリ作成開始〜「一行メモ」

0 件のコメント:

コメントを投稿