需求:历史记录里要按月份展现所有的跑步记录。
因为数据不是从服务器拉取而是存在本地,数据库用的是CoreData,以下便是通过月份进行分组,并按月份(section_month)和每条记录的时间(date)降序进行排序的查询逻辑,代码如下:
#pragma mark - core data
#pragma mark - 分组查询
- (void)getRunInfoFromCoreData{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:CD_ENTITY_NAME];
NSSortDescriptor *dateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
NSSortDescriptor *monthDescriptor = [[NSSortDescriptor alloc] initWithKey:@"section_month" ascending:NO];
[fetchRequest setSortDescriptors:@[monthDescriptor, dateDescriptor]];
[fetchRequest setResultType:NSDictionaryResultType];
fetchRequest.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@",self.isRoomrun?@"(type = 0 || type = 1)":@"type = 2"]];
_runInfofetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:SharedAppDelegate.managedObjectContext
sectionNameKeyPath:@"section_month"
cacheName:@"runInfoCache"];
[_runInfofetchedResultsController performFetch:nil];
}
fetchRequest.predicate是特定需求的查询条件,不用理睬。最终的查询结果都会封装到NSFetchedResultsController *runInfofetchedResultsController 内。
比如生成UITableView的一些关键数据:
//section个数
_runInfofetchedResultsController.sections.count;
[_runInfofetchedResultsController.sections objectAtIndex:section].numberOfObjects;
//section文字
[_runInfofetchedResultsController.sections objectAtIndex:section].name;
//特定section下的数据array,再通过indexPath.row找某条数据
NSArray *array = [_runInfofetchedResultsController.sections objectAtIndex:indexPath.section].objects;
CoreData的一些方法还是比较难找的,也比较难用,比如主键的设置和去重。但既然苹果力推,研究一下总没坏处,日后还会慢慢更新CoreData的相关操作。