我有一个项目,我需要做一个获取请求,获取核心数据实体的最新“更新”日期.当我实际检查查询返回的结果时,我看到一些相当奇怪的行为.除了包含日期的“正确”结果外,结果还包括空字典项.无论底层数据是什么样的,每次都会发生这种情况.更奇怪的是,如果我在
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
获取最大或最小项目的传统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