我正在执行获取请求,使用 NSPredicate 从初始选择中删除一些对象,并使用 NSExpression 然后检索仅托管对象的日期属性的最大值。我在其示例(Apple Developer)中使用与Apple给出的完全相同的代码,但是,似乎这个表达式在某种程度上考虑了我想要最大的属性作为数组,所以每次执行 fetch 时,应用程序都会因“无法识别的选择器”异常而崩溃(尝试将 count 消息发送给 __ NSDate 实例)。如果我将属性名称更改为 string 属性,那么我会得到 __ NSCFString 实例或等效的相同异常,这对我来说意味着它正在查找对象并使用正确的属性,但不知何故,表达式没有正确应用。
我的代码是:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"BridgeOpening" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
request.predicate = [NSPredicate predicateWithFormat:@"lastUpdated != nil && bridge.location == %@", location];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"lastUpdated"];
// Create an expression to represent the maximum value at the key path 'creationDate'
NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the maxExpression 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:@"maxDate"];
[expressionDescription setExpression:maxExpression];
[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 = nil;
NSLog(@"executing fetch");
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
NSLog(@"fetch finished");
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
NSLog(@"Minimum date: %@", [[objects objectAtIndex:0] valueForKey:@"maxDate"]);
lastUpdate = [[objects objectAtIndex:0] valueForKey:@"maxDate"];
}
}
永远不会达到'fetch finished'日志,因此执行获取请求肯定会导致异常。
有没有人知道为什么表情正在做什么似乎期待 NSArray ,或者知道我做错了什么? 我应该补充说,如果我在没有表达式(以及 NSManagedObjectResultType )的情况下执行获取请求,则没有问题,如果我的谓词是这样的,在应用表达式之前没有结果,那么没有问题。
我认为这可能与this post中遇到的问题相同,但没有公认的解决方案,原始海报给出的答案是不可接受的(使用 NSManagedObjectResultType 而不是 NSDictionaryResultType ,我认为它完全绕过了表达式,几乎可以肯定地否定了使用表达式的内存优势。
修改 我最初忘了说这个,但是我在获取请求中使用谓词时遇到了同样的问题。