我有一个Core Data to-many关系,如下所示:
Athlete(evals)<->>Eval(whosEval)
我有一个运动员的表格视图,显示数据库中的所有运动员。我想将字幕文本设置为Eval属性,假设它被称为“date_recorded”问题,每个运动员可能有超过1个eval。我需要选择evalArray中的最后一个对象,然后为每个运动员显示相关的Eval属性,因此每个运动员的字幕文本可能会有所不同。我如何为表格中的每个单元格执行此操作?这是我到目前为止所得到的:
allathletes.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Athlete Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Athlete *athlete = (Athlete *)[athleteArray objectAtIndex:indexPath.row];
cell.textLabel.text =[athlete full];
cell.detailTextLabel.text = //eval attribute "date_recorded"
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSFetchRequest *athleteRequest = [[NSFetchRequest alloc] init];
[athleteRequest setEntity:[NSEntityDescription entityForName:@"Athlete" inManagedObjectContext:_managedObjectContext]];
NSError *athleteError = nil;
NSPredicate *athletePredicate = [NSPredicate predicateWithFormat:@"full == %@", athlete.full];
[athleteRequest setPredicate:athletePredicate];
NSArray *results = [_managedObjectContext executeFetchRequest:athleteRequest error:&athleteError];
Athlete *currentAthlete = [results objectAtIndex:0];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"whosEval == %@", currentAthlete];
[request setPredicate:predicate];
NSEntityDescription *eval = [NSEntityDescription entityForName:@"Eval" inManagedObjectContext:_managedObjectContext];
[request setEntity:eval];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"date_recorded"
ascending:NO
selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil){
//handle error
}
NSMutableArray *lastEvalArray = mutableFetchResults;
Eval *lastEval = lastEvalArray.lastObject;
cell.detailTextLabel.text = lastEval.date_recorded;
return cell;
}
答案 0 :(得分:1)
如果date_recorded
是NSDate
属性,则可以执行
Athlete *athlete = (Athlete *)[athleteArray objectAtIndex:indexPath.row];
NSDate *lastRecorded = [athlete valueForKeyPath:@"@max.evals.date_recorded"];
然后使用NSDateFormatter
将lastRecorded
转换为NSString
和
将其分配给cell.detailTextLabel.text
。