documentation举例说明如何仅检索简单值,而不是托管对象。这会记住很多使用别名和函数的SQL来仅检索计算值。所以,其实非常令人讨厌的东西。为了得到从一堆记录的最小日期,这是用来在Mac上:如何在iPhone上使用像这样的表达式获取请求?
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"creationDate"];
// Create an expression to represent the minimum value at the key path 'creationDate'
NSExpression *minExpression = [NSExpression expressionForFunction:@"min:" arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the minExpression and returning a date.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:@"minDate"];
[expressionDescription setExpression:minExpression];
[expressionDescription setExpressionResultType:NSDateAttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
NSLog(@"Minimum date: %@", [[objects objectAtIndex:0] valueForKey:@"minDate"];
}
}
[expressionDescription release];
[request release];
不错,我虽然 - 但有一个深入探讨NSExpression -expressionForFunction:arguments:事实证明,iPhone OS不支持min:
功能。
那么,可能有一种漂亮的方式来使用iPhone上的这种东西自己的功能呢?因为我已经担心的事情是,我要如何根据计算出的地图上的目标距离(基于位置的东西)对表格进行排序。