0

私のアプリはログブックのようなものです。私は1日に発生するイベントの証拠を保持しています。基本的に、「date」属性を持つエンティティ(テーブルビューに表示)があります。新しいイベントを保存すると、[NSDatedate]を使用して現在の日付が保存されます。すべてのイベントが日ごとに並べ替えられて表示されるように、テーブルビューを整理するにはどうすればよいですか?ヒントをいただければ幸いです。

4

1 に答える 1

3

sectionNameKeyPathのパラメーターを使用NSFetchedResultsControllerして、結果を日付別に区分する必要があります。

ここここにいくつかの例があります。

基本的に、使用する属性を sectionNameKeyPath パラメーターとして設定します。これは次のようになります。

fetchedResultsController = [[NSFetchedResultsController alloc]
                            initWithFetchRequest:fetchRequest
                            managedObjectContext:managedObjectContext
                              sectionNameKeyPath:@"date"
                                       cacheName:nil];

次に、データ ソース デリゲート コードは次のようになります。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[fetchedResultsController sections] count];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [fetchedResultsController sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

編集:項目を日ごとにグループ化するには、管理対象オブジェクトの一時的なプロパティを作成する必要があります。基本的には、実際の日付から派生した日付文字列です。

これらはいつものように .h / .m の一番上に置かれます

@property (nonatomic, strong) NSString *sectionTitle;

@synthesize sectionTitle;

プロパティを作成したので、そのアクセサーをオーバーライドして、要求されたときに実際にタイトルを設定します。

-(NSString *)sectionTitle
{
   [self willAccessValueForKey:@"date"];
    NSString *temp = sectionTitle;
   [self didAccessValueForKey:@"date"];

   if(!temp)
   {
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      [formatter setDateFormat:@"d MMMM yyyy"]; // format your section titles however you want
      temp = [formatter stringFromDate:date];
      sectionTitle = temp;
   }
   return temp;
}

このコードは、sectionTitle が既にキャッシュされているかどうかを実際に確認し、再作成せずに再利用することに注意してください。過去のオブジェクトの日付が変更されることを期待または許可している場合は、sectionTitle も更新する必要があります。その場合は、日付自体のミューテーターも上書きし、クリアする行を追加する必要があります。 sectionTitle (次にタイトルが要求されたときに再作成されるようにするため)。

- (void)setDate:(NSDate *)newDate {

    // If the date changes, the cached section identifier becomes invalid.
    [self willChangeValueForKey:@"date"];
    [self setPrimitiveTimeStamp:newDate];
    [self didChangeValueForKey:@"date"];

    [self setSectionTitle:nil];
}

そして最後に、sectionNameKeyPathfor をfetchedResultsControllerに変更する必要があります@"sectionTitle"

Apple にはサンプル プロジェクトがあり、同様の動作を見たい場合に参照できます。

于 2012-06-25T18:57:38.630 に答える