我想填充數組postCaptions。 我需要將此數組返回給我的表視圖的numberOfRowsInSection,但它每次都返回一個空數組。數組返回PFQuery之外的空數組與解析
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'以異步方式工作。打印行在數據返回之前執行。將打印線放入完成塊。 – vadian
是的,但我需要延遲numberOfRowsInSection的調用,直到完成塊完成加載,並因此給出了postCaptions的值 –
'numberOfRowsInSection'從框架中調用。填充數據源數組並調用'reloadData()'。 – vadian