核心数据:尝试查找实体中属性的最小日期 [英] Core Data: trying to find minimum date for an attribute in an entity
问题描述
我试图在Core Data中找到特定属性中最早的日期。我找到了核心数据编程指南中的一个例子,看起来正是这样,但在运行它时会得到无法识别的选定错误。
I'm trying to find the oldest date in a particular attribute in Core Data. I've found an example in the Core Data Programming Guide that purports to do exactly that, but keep getting an unrecognized selected error when I run it.
我的代码(只有从Apple例子的最小更改):
My code (with only minimal changes from the Apple Example):
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext: ctx];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"startedAt"];
// 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 = [ctx executeFetchRequest:request error:&error];
错误:
-[NSCalendarDate count]: unrecognized selector sent to instance ...
这是奇怪的,因为1)NSCalendarDate已弃用,2)我绝对不会调用计数。
Which is strange given that 1) NSCalendarDate is deprecated and 2) I'm definitely not calling count.
任何帮助将是最感激的!
Any help would be most appreciated!
推荐答案
为什么不只是添加一个排序描述符来排序 startedDate
请求返回1个对象?
Why not just add a sort descriptor to sort by startedDate
ascending, and then only have the fetch request return 1 object?
这篇关于核心数据:尝试查找实体中属性的最小日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!