我有一个项目,我需要做一个获取最近更新的获取请求'核心数据实体的日期。当我实际检查查询返回的结果时,我看到一些相当奇怪的行为。除了正确的'结果包含结果日期还包括空字典项。无论基础数据是什么样的,每次都会发生这种情况。更奇怪的是,如果我打开xcode中的sql登录并对sqllite db执行记录查询,它会生成正确的结果而没有额外的条目。我不太确定我在这里做错了什么,我们将不胜感激。
构建和执行查询的函数:
func queryForContactDate(context:NSManagedObjectContext) -> AnyObject?
{
var expressionDescriptions = [AnyObject]();
let expressionDescription = NSExpressionDescription()
// Name the column
expressionDescription.name = "maxUpdated"
// Use an expression to specify what aggregate action we want to take and
// on which column. In this case max on the update_at column
expressionDescription.expression = NSExpression(format: "@max.updated_at")
// Specify the return type we expect
expressionDescription.expressionResultType = .DateAttributeType
// Append the description to our array
expressionDescriptions.append(expressionDescription)
// Build out our fetch request the usual way
let request = NSFetchRequest(entityName: Contact.entityName())
// Specify we want dictionaries to be returned
request.resultType = .DictionaryResultType
// Hand off our expression descriptions to the propertiesToFetch field.
request.propertiesToFetch = expressionDescriptions
// Our result is going to be an array of dictionaries.
var results:[[String:AnyObject]]?
// Perform the fetch. This is using Swfit 2, so we need a do/try/catch
do {
results = try context.executeFetchRequest(request) as? [[String:AnyObject]]
} catch _ {
// If it fails, ensure the array is nil
results = nil
}
return results![0];
}
如果我在最后放置一个断点并打印出它产生的结果:
Printing description of results:
▿ Optional([[:], ["maxUpdated": 2015-12-30 20:05:31 +0000]])
▿ Some : 2 elements
- [0] : 0 elements
▿ [1] : 1 elements
▿ [0] : 2 elements
- .0 : "maxUpdated"
- .1 : 2015-12-30 20:05:31 +0000
答案 0 :(得分:1)
获取最大或最小项目的传统Core Data方法是使用获取限制为1进行查询并对该键进行排序。与此Objective-C代码一样:
+ (NSFetchRequest *) requestForStatusWithMaxID {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName: kAMStatusEntity];
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey: kAMTwID ascending:NO];
request.sortDescriptors = @[sd];
request.fetchLimit = 1;
return request;
} // +requestForStatusWithMaxID
修改updated_at
属性的上述内容非常简单。