OGeek|极客世界-中国程序员成长平台

标题: ios - 从 CoreData 上的不同属性中获取前 1 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:33
标题: ios - 从 CoreData 上的不同属性中获取前 1

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

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

+---+-------+-------+----- ----------+ | |用户名 |留言 |时间戳 | +---+-------+-------+----- ----------+ | 1 |约翰 |你好 | 486380161.723 | | 2 |马克 |电子表格 | 486380264.723 | | 3 |约翰 |仅供引用 | 486380366.723 | | 4 |约翰 |再见 | 486557497.271 | | 5 |马克 |你好吗? | 486557597.274 | | 6 |马里奥 |什么? | 486558597.274 | +---+-------+-------+----- ----------+

这就是我应该得到的结果。

+---+-------+-------+----- ----------+ | |用户名 |留言 |时间戳 | +---+-------+-------+----- ----------+ | 6 |马里奥 |什么? | 486558597.274 | | 5 |马克 |你好吗? | 486557597.274 | | 4 |约翰 |再见 | 486557497.271 | +---+-------+-------+----- ----------+

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

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

谢谢, 马里奥



Best Answer-推荐答案


可以分两次提取,但有一点我会在谈到它时提及。

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

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

    let maxTimestampExpression = NSExpression(format: "maxtimestamp)")
    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;
}])

获取完整记录需要第二次提取。如果上一次 fetch 的结果在一个名为 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 提取,您将获得符合您要求的完整托管对象。

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

关于ios - 从 CoreData 上的不同属性中获取前 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37730879/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4