Swift Fetch 请求在结果中返回空项

标签 swift core-data aggregate-functions nsfetchrequest

我有一个项目,我需要执行获取请求以获取核心数据实体的最新“更新”日期。然而,当我实际检查查询返回的结果时,我看到了一些相当奇怪的行为。除了包含日期的“正确”结果外,结果还包括一个空字典项。无论底层数据是什么样子,这种情况每次都会发生。更奇怪的是,如果我在 xcode 中打开 sql 日志记录并对 sqllite 数据库执行记录的查询,它会产生正确的结果,没有额外的条目。我不太确定我在这里做错了什么,我们将不胜感激。

构建和执行查询的函数:

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

为您的 updated_at 属性修改以上内容将非常简单。

关于Swift Fetch 请求在结果中返回空项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620174/

相关文章:

sql - 在PostgreSQL的同一查询中如何使用两个SUM()聚合函数?

swift - 核心数据迁移 - Appstore 构建在 iOS 8 设备上崩溃,在 iOS 9 上运行

ios - 核心数据在更新应用程序时创建额外的空存储

sql - 如何在 Sql Server 中的 SELECT CASE 子句的比较中使用 COUNT()?

ios - SceneKit 几何图形看起来像是一场小故障灾难

ios - 尝试返回要在 PickerView 中使用的数据库行

mysql - SQL 仅选择列上具有最大值的行

ios - 如何快速将特定格式转换为任何对象?

ios - 我正在使用 UILabel 和 UITextField,我想转换 3 个字母组中的所有文本

swift - Swift 中的嵌套异步调用