1
这是我第一次尝试使用CoreData,并且在从表中获取最大日期时遇到了一些麻烦。使用CoreData获取最大值
这基本上就是我想要做的事:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Radar" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"modifiedOn"];
NSExpression *maxDate = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"maxDate"];
[expressionDescription setExpression:maxDate];
[expressionDescription setExpressionResultType:NSDateAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
NSError *error = nil;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
NSLog(@"%d", [objects count]);
NSLog(@"MAx date: %@", [[objects objectAtIndex:0] valueForKey:@"modifiedOn"]);
}
}
这个代码在某种程度上确实的我想的正好相反,打印最小日期。由于我刚刚开始使用CoreData,很明显我出错了,但是什么?
查看第二个答案在这里:http://stackoverflow.com/questions/4789033/querying-max-min-and-other-via-core-data – sho 2012-02-09 23:43:23
@sho - 我得到它的工作使用你指出我的答案,然而,官方文件使用我粘贴在问题上的代码。任何想法为什么这个代码几乎是来自文档的代码的副本不工作?谢谢 – Raphael 2012-02-10 01:05:05