ios - 获取每个 "OtherUser"解析核心数据库的最新记录

标签 ios database swift parsing parse-platform

我正在使用 Parse 在基于 Swift 的 iOS 应用程序中开发一个简单的聊天系统。到目前为止,我在 Parse 中定义了两个类:User(定义用户)和 Message(定义发送给用户的单个消息)。这是我的消息类字段:

UserFromID (pointer): points to the User object that sent the message
UserToID (pointer): points to the User object that receives the message
createdAt (DateTime): creation point in time (built-in field)
Content (string): the textual message to show the user

在对话选择屏幕上,我想显示一个表格,列出已登录用户与之交互过的每个用户。我还想获取该对话中记录的最后一条消息,无论该对话中的两个用户之间是谁发送的。我已经能够做到这一点,但以一种浪费的方式:

// get all messages sent FROM and TO the user
let primaryObj = PFObject(withoutDataWithClassName: "_User", objectId: self.userID)
let fromQuery = PFQuery(className: "Message")
let toQuery = PFQuery(className: "Message")

// add constraints to both queries
fromQuery.whereKey("UserFromID", equalTo: primaryObj)
toQuery.whereKey("UserToID", equalTo: primaryObj)

// generate the concatenated query, include User access, and return sorted
let masterQuery = PFQuery.orQueryWithSubqueries([fromQuery, toQuery])
masterQuery.includeKey("UserFromID")
masterQuery.includeKey("UserToID")
masterQuery.orderByDescending("createdAt")

// execute the query, and perform response logic
masterQuery.findObjectsInBackgroundWithBlock({
    (results: [PFObject]?, error: NSError?) -> Void in
    // query logic goes here...
})

这可行,但它会返回所有用户之间发送到登录用户和从登录用户发送的所有消息。我只想要每个用户之间的最新消息。当前的解决方案会产生大量开销,我认为 Parse 对对象请求的硬限制是 1000。对于两个用户来说,在一个月甚至一周内相互发送 1000 条消息非常容易,具体取决于用户。我的解决方案需要每个设备进行许多大型查询,忽略缓存计划,并且我的请求仅来自聊天就会激增。特别是当数据要求如此之低时。

我希望 fromQuery 和 toQuery 做的是在每个唯一的 otherUser 基础上获取具有最大的createdAt字段(DateTime)的消息。

最佳答案

我认为你应该做的是对 fromQuery 和 toQuery 进行限制,如下所示:

fromQuery.limit = 1
toQuery.limit = 1

这样您将始终只得到 2 个结果。然后,当您获得结果时,只需比较两个结果的createdAt属性即可。

关于ios - 获取每个 "OtherUser"解析核心数据库的最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35748055/

相关文章:

ios - 火存储 : Calls with of async function with SnapshotListener and in a cycle with DispatchGroup cause a crash

ios - 将NSMutableArray数据插入一键多类值的Dictionary

通过 NSURLConnection sendAsynchronousRequest 下载 Ios 表格单元格图像会导致表格单元格删除时崩溃

ios - 通过 AdMob 集成 MillenialMedia 中介时出错

php - 删除PHP MySQL查询错误

mysql - 如何在线存储转换为sql的access数据库

java - 根据从数据库中检索到的文本选择 jButton

swift - 如何为长时间按下的 UIButton 创建目标(重复处理程序)?

ios - 关闭弹出窗口时执行功能

SwiftUI:更改基于 NavigationBarTitle 的 TabbedView 标签的更好方法