【发布时间】:2017-08-30 11:15:02
【问题描述】:
我正在尝试填充数组 postCaptions。 我需要将此数组返回给我的表格视图的 numberOfRowsInSection,但它每次都返回一个空数组。
var postCaptions = [String]()
query2.whereKey("userid", equalTo: PFUser.current()?.objectId!)
query2.findObjectsInBackground(block: { (objects, error) in
if let userPosted = objects {
for object in userPosted {
if let userPost = object as? PFObject {
self.postImageFiles.append(userPost["userPostImage"] as! PFFile)
self.postLocation.append(userPost["userPostLocation"] as! String)
self.postCaptions.append(userPost["postCaption"] as! String)
print(self.postCaptions.count) //returns value of 2 for the two posts that I've made
self.tableView.reloadData()
self.refresher.endRefreshing()
}
}
}
})
print(self.postCaptions.count) //Returns empty array
我知道问题在于线程的顺序,我理解这一点,但我不确定我能做些什么来使数组在查询之外保持填充状态。我已经将其视为解决此问题的一种方法,但是对于如何在代码中解决此问题,我真的没有找到直接的答案。如果有人能提供一个适用于我的代码的答案,那就太棒了!:) 我已经被这个问题困扰了一个多星期了
var postCaptions = [String]() {
didSet {
// Do any execution that needs to wait for postCaptions here.
}
}
**cellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userPhotoFeedCell", for: indexPath) as! FeedCell
if PFUser.current()?.objectId != nil {
cell.userUsername.text = PFUser.current()?.username
}
//downloads images for user profile pic
imageFiles[indexPath.row].getDataInBackground { (data, error) in
if let imageData = data {
let downloadedImage = UIImage(data: imageData)
cell.userProfilePic.image = downloadedImage
}
}
//downloades images and items to populate user post
postImageFiles[indexPath.row].getDataInBackground { (data, error) in
if let userPostImageData = data {
let downloadedUserPostImage = UIImage(data: userPostImageData)
cell.userFeedPhoto.image = downloadedUserPostImage
}
}
cell.postLocation.text = postLocation[indexPath.row]
cell.postCaption.text = postCaptions[indexPath.row]
cell.userFeedPhoto.image = UIImage(named: "OrangeFuego")
cell.userProfilePic.image = UIImage(named: "usericon.png")
return cell
}
【问题讨论】:
-
findObjectsInBackground异步工作。在返回数据之前执行打印行。将打印行放入完成块中。 -
是的,但我需要延迟 numberOfRowsInSection 的调用,直到完成块加载完成,因此给 postCaptions 一个值
-
numberOfRowsInSection从框架中调用。填充您的数据源数组并调用reloadData()。
标签: arrays swift parse-platform tableview pfquery