从 CoreData 的不同属性中获取前 1

Get top 1 from distinct attribute on CoreData

您好,我有一个 table,格式如下所示。

我想建立一个历史视图,所以我需要来自不同用户的最后消息,按时间戳排序!

+---+-------------------+-------------------+---------------+ | | Username | Message | Timestamp | +---+-------------------+-------------------+---------------+ | 1 | John | Hello | 486380161.723 | | 2 | Mark | Spreadsheet | 486380264.723 | | 3 | John | FYI | 486380366.723 | | 4 | John | Bye | 486557497.271 | | 5 | Mark | How are you? | 486557597.274 | | 6 | Mario | What? | 486558597.274 | +---+-------------------+-------------------+---------------+

这就是我的结果。

+---+-------------------+-------------------+---------------+ | | Username | Message | Timestamp | +---+-------------------+-------------------+---------------+ | 6 | Mario | What? | 486558597.274 | | 5 | Mark | How are you? | 486557597.274 | | 4 | John | Bye | 486557497.271 | +---+-------------------+-------------------+---------------+

现在,我得到所有不同的 username,迭代每个并查询该用户名的消息,按时间戳排序,limit(1)

我对这个解决方案不满意所以有人可以帮助我找到更好的解决方案吗?

谢谢, 马里奥

可以分两次提取完成,但有一个注意事项,我会在谈到它时提及。

第一次提取获取每个用户名和最近的时间戳:

    let maxTimestampRequest = NSFetchRequest(entityName: "Entity")
    maxTimestampRequest.resultType = .DictionaryResultType

    let maxTimestampExpression = NSExpression(format: "max:(timestamp)")
    let maxTimestampExpressiondescription = NSExpressionDescription()
    maxTimestampExpressiondescription.name = "maxTimestamp"
    maxTimestampExpressiondescription.expression = maxTimestampExpression
    maxTimestampExpressiondescription.expressionResultType = .DoubleAttributeType

    maxTimestampRequest.propertiesToFetch = ["username", maxTimestampExpressiondescription]
    maxTimestampRequest.propertiesToGroupBy = ["username"]

执行该提取,您将获得一组字典。每个字典都包含一个用户名和该用户名的最新时间戳:

Optional([{
    maxTimestamp = "486557497.271";
    username = John;
}, {
    maxTimestamp = "486558597.274";
    username = Mario;
}, {
    maxTimestamp = "486557597.274";
    username = Mark;
}])

获取完整记录需要第二次获取。如果上一次获取的结果在一个名为 results

的数组中
    var predicates = [NSPredicate]()
    for maxTimestampInfo in results! {
        let username = maxTimestampInfo["username"]!
        let timestamp = maxTimestampInfo["maxTimestamp"]!
        let partialPredicate = NSPredicate(format: "username=%@ and timestamp=%@", argumentArray:[ username, timestamp ])
        predicates.append(partialPredicate)
    }
    let completePredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)

    let fetch = NSFetchRequest(entityName: "Entity")
    fetch.predicate = completePredicate

执行 that fetch,您将获得符合您要求的完整托管对象。

需要注意的是,第二次提取中的谓词可能非常大,具体取决于您拥有的用户数量。