【发布时间】:2016-05-12 15:28:50
【问题描述】:
我已经很接近了……但一定是错过了什么。
我当地的数据库有一个包含各种详细信息的高尔夫球场列表,其中包括州、州名的第一个字母(A、C、D、)等...NSFetchedResultsController 正在获取一个列表课程,并且正在(或正在)工作得很好,展示了我有记录的课程的所有州。
无论如何......部门负责人似乎正在工作......但我的州现在正在复制每个给定州拥有的课程数量。
代码和屏幕截图如下。我错过了什么?!?一定是很明显的东西。
-(NSFetchedResultsController *)fetchedResultsController {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Courses"
inManagedObjectContext:_managedObjectContext];
request.entity = entity;
request.sortDescriptors = [NSArray arrayWithObject:
[NSSortDescriptor
sortDescriptorWithKey:@"locState"
ascending:YES
selector:@selector(caseInsensitiveCompare:)]];
request.returnsDistinctResults = YES;
request.fetchBatchSize = 20;
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"locStateSectionHead"
cacheName:nil];
frc.delegate = self;
NSError *error = nil;
if (![frc performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
self.fetchedResultsController = frc;
return _fetchedResultsController;
}
然后是其余的 tableView 设置:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
if ([[_fetchedResultsController sections] count] > 0) {
id <NSFetchedResultsSectionInfo> sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
} else {
return 0;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo name];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self.fetchedResultsController sectionIndexTitles];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"stateCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell...
Courses *course_info = [_fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = course_info.locState;
return cell;
}
【问题讨论】:
-
所以你希望部分是第一个字母,而行是状态,例如第一部分是“A”,有 4 行,“阿拉巴马州”,“阿拉斯加州”,“亚利桑那州”, “阿肯色州”?大概当您点击一个单元格时,它会显示一个新的表格视图,其中包含所选州的所有课程?
-
正确。过去就是这样,尽管当然没有节标题。
标签: objective-c uitableview core-data nsfetchedresultscontroller uitableviewsectionheader