我使用了NSExpression方法expressionForFunction:arguments:平均值,sum,min,max,count成功,代码与下面相同(在Apple的文档中给出)。
但是当谈到标准偏差(stddev :)或中位数(中位数:)时。编译时我没有错误,但我只是在executeFetchRequest行上得到“SIGABRT”信号。
在我的代码中,我无法找出平均值,总和,最小值,最大值,计数和stddev或中位数之间的差异。 NSExpression类在这些参数和返回对象之间没有区别,唯一的区别是可用性(Mac OS 10.4适用于那些工作,10.5适用于其他。
我正在使用Xcode 4.2,我的应用程序正在使用ARC定位iOS 5。
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"myEntity" inManagedObjectContext:app.managedObjectContext];
[request setEntity:entity];
[request setPredicate:[NSPredicate predicateWithFormat:@"something == %d",2]];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"anAttribute"];
// Create an expression to represent the minimum value at the key path
NSExpression *statExpression = [NSExpression expressionForFunction:@"stddev:" arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the statExpression and returning a float.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:@"statData"];
[expressionDescription setExpression:statExpression];
[expressionDescription setExpressionResultType:NSFloatAttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error = nil;
NSArray *objects = [app.managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
float result = [[[objects objectAtIndex:0] valueForKey:@"statData"] floatValue];
感谢您的帮助。