我正在尝试在 mongoDB 上创建“用户”和“评论”之间的连接,以便对我的应用程序发表评论。
这是我的代码:
let query = PFQuery(className: "comments")
query.whereKey("to", equalTo: commentuuid.last!)
query.skip = count - self.page
query.addAscendingOrder("createdAt")
query.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
if error == nil {
// Clean up
self.usernameArray.removeAll(keepingCapacity: false)
self.avaArray.removeAll(keepingCapacity: false)
self.commentArray.removeAll(keepingCapacity: false)
self.dateArray.removeAll(keepingCapacity: false)
// find related objects
for object in objects! {
let infoQuery = PFQuery(className: "_User")
infoQuery.getObjectInBackground(withId: object.object(forKey: "id") as! String, block: { (test: PFObject?, error: Error?) in
if error == nil {
print("YES")
self.usernameArray.append(test!.object(forKey: "username") as! String)
} else {
print(error!.localizedDescription)
}
})
self.commentArray.append(object.object(forKey: "comment") as! String)
self.dateArray.append(object.createdAt)
self.tableView.reloadData()
// Scroll to bottom
self.tableView.scrollToRow(at: IndexPath(row: self.commentArray.count - 1, section: 0), at: .bottom, animated: true)
}
} else {
print(error!.localizedDescription)
}
})
这些行执行得很好:
self.commentArray.append(object.object(forKey: "comment") as! String)
self.dateArray.append(object.createdAt)
但事实并非如此:
let infoQuery = PFQuery(className: "_User")
infoQuery.getObjectInBackground(withId: object.object(forKey: "id") as! String, block: { (test: PFObject?, error: Error?) in
if error == nil {
print("YES")
self.usernameArray.append(test!.object(forKey: "username") as! String)
} else {
print(error!.localizedDescription)
}
})
我尝试在 cellForRowAt 函数中打印 usernameArray 和 dateArray(只是为了查看差异)。
当我启动 View 时,usernameArray 为空,而 dateArray 不为空。如果我滚动一点,usernameArray 就会被填满(但我需要滚动来填充数组,这是 Not Acceptable )。
最佳答案
可能是因为您在检索数据之前调用了 UI 相关方法:
self.commentArray.append(object.object(forKey: "comment") as! String)
self.dateArray.append(object.createdAt)
let infoQuery = PFUser.query()!
infoQuery.getObjectInBackground(withId: object.object(forKey: "id") as! String, block: { (test: PFObject?, error: Error?) in
if error == nil {
print("YES")
self.usernameArray.append(test!.object(forKey: "username") as! String)
} else {
print(error!.localizedDescription)
}
// These two methods were the issue.
self.tableView.reloadData()
// Scroll to bottom
self.tableView.scrollToRow(at: IndexPath(row: self.commentArray.count - 1, section: 0), at: .bottom, animated: true)
})
您应该考虑:
- 使用子类
PFObject
来避免访问原始字典,这可能会因拼写错误而导致错误。 - 将关键字
object
替换为更好的关键字(根据您的上下文,comment
)
关于swift - 在 Swift 中与 mongoDB 和 Parse 结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45039443/