我从书中找到的教程中构建了一些代码。它可以工作,我能够在 tableView 中成功显示来自 CoreData 的数据。我现在想识别 fetchRequest 返回的数据/对象。我觉得自己像个傻瓜,因为我无法理解足够的语法来隔离包含我的数据数组的对象。这是我难以理解的代码片段:
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Sessions" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
//NSLog(@"Entity is set to: %@", entity);
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"refid" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
//[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
Sessions *info = [_fetchedResultsController objectAtIndexPath:indexPath];
//Format cell data ready to be displayed
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, dd LLL yyyy"];
NSString *dateString = [dateFormat stringFromDate:info.date];
NSNumber *dist1Nbr = info.dist1;
int dist1Int = [dist1Nbr integerValue];
float distIntKorM = ([dist1Nbr integerValue])/1000;
NSString *dist1StrMeters = [[NSString alloc] initWithFormat:@"%i", dist1Int];
NSString *dist1StrKorM = [[NSString alloc] initWithFormat:@"%.01f", distIntKorM];
//Select image to display
if ([info.sport isEqualToString:@"Run"]) {
UIImage *image = [UIImage imageNamed:@"trainers-15x10.png"];
cell.imageView.image = image;
cell.textLabel.text = [[NSString alloc] initWithFormat:@"%@: (%@),", dateString, info.sport];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:@"Type: %@, Dist: %@", info.sessiontype, dist1StrKorM];
} else if ([info.sport isEqualToString:@"Other"]) {
UIImage *image = [UIImage imageNamed:@"weights-15x10.png"];
cell.imageView.image = image;
cell.textLabel.text = [[NSString alloc] initWithFormat:@"%@: (%@),", dateString, info.sport];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:@"Type: %@, Dist: %@", info.sessiontype, dist1StrKorM];
}
}
如果有人可以帮助我,将不胜感激。