【发布时间】:2020-05-04 09:50:34
【问题描述】:
在 ViewController 中,我设置了两个变量,分别称为 post 和 user,类型为 Post 和 aUser,我创建的这两个类型包含所有需要的信息。
VC的ViewDidLoad方法如下:
override func viewDidLoad() {
super.viewDidLoad()
updateViewDetail()
}
它调用 updateViewDetail() 方法从 Firebase 实时数据库中检索正确的用户和发布对象:
func updateViewDetail(){
Api.Post.observePost(with: postID) { (post) in
let postretrieved = post
print("post id inside \(postretrieved.caption)")
guard let postUid = postretrieved.uid else{
return
}
self.fetchUsers(uid: postUid) {
self.post = post
self.tableView.reloadData()
}
print("the post in the function : \(post.id)")
}
}
func fetchUsers(uid: String, completed: @escaping ()-> Void){
Api.theUser.observeUser(withID: uid) { (user) in
self.user = user
print("the user in the function is : \(user.id)")
completed()
}
}
这些方法的目标是将从数据库中检索到的帖子和用户与我在 ViewController 中声明的内容相等,以便以后可以在 TableView 上显示它们。
问题是当我尝试打印用户或在方法中发布时(如代码所示)我看到正确的输出,用户被正确检索和打印。 但是当我尝试在 viewDidLoad 方法中打印它时,它打印为零。
self.post = post 和 self.user = user 关联似乎无法正常工作,并且不等于 VC 变量与方法中检索到的变量相等。你知道我该如何解决这个问题吗?
编辑 1:在 ViewController 中设置的变量 user 和 post 用于使用自定义 UITableViewCell 设置 UITableView 中的值。代码在这里: 1) 首先我将 tableViewDatasource 设置为等于 ViewController。
override func viewDidLoad() {
super.viewDidLoad()
updateViewDetail(onUserRetrieved: { (user) in
self.user = user
}) { (post) in
self.post = post
}
tableView.dataSource = self
}
然后我让VC按照协议设置需要的方法:
extension DetailViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! HomeTableViewCell
cell.post = self.post
cell.user = self.user
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
}
当我运行应用程序时,我收到一个错误,说明 HomeTableViewCell 的 post 和 user 中的值为零,因此应用程序崩溃了。
【问题讨论】:
-
这可能是因为代码是异步运行的。
-
您正在执行异步调用,因此
viewDidLoad中的打印语句在从 Firebase 返回数据之前执行。所以你的代码很可能运行良好。在fetchUsers中,尝试从completed闭包打印。 -
这是一篇关于它的文章,What “asynchronous” means。对于社区来说,这个问题一直都在出现,是否有一个合适的问题可以作为重复问题的首选关闭?
标签: ios swift variables methods viewdidload