Swift获取请求返回结果中的空项

pbu*_*eit 8 core-data aggregate-functions nsfetchrequest swift

我有一个项目,我需要做一个获取请求,获取核心数据实体的最新"更新"日期.当我实际检查查询返回的结果时,我看到一些相当奇怪的行为.除了包含日期的"正确"结果外,结果还包括空字典项.无论基础数据是什么样的,每次都会发生这种情况.更奇怪的是,如果我打开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];
}
Run Code Online (Sandbox Code Playgroud)

如果我在最后放置一个断点并打印出它产生的结果:

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
Run Code Online (Sandbox Code Playgroud)

ado*_*oho 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
Run Code Online (Sandbox Code Playgroud)

为您的财产修改上述内容将非常简单updated_at