您好我有一张表格,其格式如下所示。
我想构建一个历史记录视图,所以我需要来自不同用户的最后消息,按时间戳排序!
+---+-------------------+-------------------+---------------+
| | 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)
查询按时间戳排序的用户名的消息。
我对这个解决方案不满意所以任何人都可以帮助我做一个更好的解决方案吗?
谢谢, 马里奥
答案 0 :(得分:3)
这有可能分两次进行,但有一点需要注意,当我到达它时,我会提到它。
第一次获取获取每个用户名和最近的时间戳:
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
执行 获取,您将获得符合要求的完整托管对象。
需要注意的是,第二次获取中的谓词可能非常大,具体取决于您拥有的用户数。