2
我试图获取核心数据中实体中属性的最大值。苹果有一个很好的例子here如何做到这一点;但是,它不适合我。我在我的moc中有10个对象,下面的代码总是返回一个大小为0的数组。任何人都可以告诉我我做错了什么?谢谢!获取实体中值的最大值
NSManagedObjectContext* moc = [self managedObjectContext];
// set the idx to the maximum value
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Transaction"
inManagedObjectContext:moc];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression* keyPathExpression = [NSExpression expressionForKeyPath:@"idx"];
// Create an expression to represent the minimum value at the key path 'creationDate'
NSExpression* maxExpression = [NSExpression expressionForFunction:@"max:"
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:@"maxIdx"];
[expressionDescription setExpression:maxExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];
// 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 = [moc executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
int newIdx = [[[objects objectAtIndex:0] valueForKey:@"maxIdx"] intValue] + 1;
[self setPrimitiveIdx:[NSNumber numberWithInt:newIdx]];
} else {
[self setPrimitiveIdx:[NSNumber numberWithInt:1]];
}
}
+1打我给它。我认为最可能的错误是拼写错误'交易'或关键路径。我会在没有表达式的情况下运行抓取并查看返回的结果。 – TechZen 2011-02-27 16:26:19
是的,我检查过拼写和其他几次。商店中有10个交易对象,idx是一个整数32.我在应用程序中使用垃圾收集,所以发布应该没有关系。我会检查错误日志。 – Cayden 2011-02-27 20:51:12
一旦持久性存储已被保存,看起来上述内容将起作用;但在此之前。尽管如此,我仍然可以在一个替代解决方案中完全使用它。 – Cayden 2011-02-28 15:01:20