需求:歷史記錄里要按月份展現(xiàn)所有的跑步記錄氛驮。
因?yàn)閿?shù)據(jù)不是從服務(wù)器拉取而是存在本地葛作,數(shù)據(jù)庫用的是CoreData,以下便是通過月份進(jìn)行分組醒第,并按月份(section_month)和每條記錄的時間(date)降序進(jìn)行排序的查詢邏輯,代碼如下:
#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是特定需求的查詢條件进鸠,不用理睬稠曼。最終的查詢結(jié)果都會封裝到NSFetchedResultsController *runInfofetchedResultsController 內(nèi)。
比如生成UITableView的一些關(guān)鍵數(shù)據(jù):
//section個數(shù)
_runInfofetchedResultsController.sections.count;
[_runInfofetchedResultsController.sections objectAtIndex:section].numberOfObjects;
//section文字
[_runInfofetchedResultsController.sections objectAtIndex:section].name;
//特定section下的數(shù)據(jù)array,再通過indexPath.row找某條數(shù)據(jù)
NSArray *array = [_runInfofetchedResultsController.sections objectAtIndex:indexPath.section].objects;
CoreData的一些方法還是比較難找的客年,也比較難用霞幅,比如主鍵的設(shè)置和去重。但既然蘋果力推量瓜,研究一下總沒壞處司恳,日后還會慢慢更新CoreData的相關(guān)操作。