2011年9月26日月曜日

CoreDataを利用したヘッダーとセクションインデックスの使用法

iOSでTableViewのヘッダーとセクションインデックスを指定するときに、
CoreDataを使用するとコーディングが楽になります。

sectionNameKeyPathに設定したいヘッダー、セクションインデックスを指定する

NSFetchedResultsController *_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"sectionName" cacheName:nil];

ヘッダーの設定
セクションごと文字列を返す


//ヘッダーを設定する
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    //nameがsectionPathで指定した文字列になる
    return [[[fetchedResultsController sections] objectAtIndex:section] name];
}

セクションインデックスはテーブル作成時に配列で返す

//セクションインデックスを設定する
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *indexTitleArray = [[[NSMutable Arrayalloc] init] autorelease];

    for (int i = 0; i < [[fetchedResultsController sections] count]; i++) {
        //nameがsectionPathで指定した文字列になる
        NSString *indexString = [[[fetchedResultsController sections] objectAtIndex:i] name];
        [indexTitleArray addObject:indexString];
    }
    return indexTitleArray;
}

0 件のコメント:

コメントを投稿