func loadYelpComments(){
guard let business = business else {return}
guard let _ = tableView else {return}
guard let businessID = business.id else {return}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
HTTPHelper.getYelpComments(for: businessID, completionHandler: { data in
let json = JSON(data)
let reviews = json["reviews"].arrayValue.map({return $0.dictionaryValue})
var commentDate: Date?
for (index, review) in reviews.enumerated(){
let userDictionary = review["user"]?.dictionary
if let dateString = review["time_created"]?.stringValue{
commentDate = dateFormatter.date(from: dateString)
}
let yelpComment = YelpComment(rating: review["rating"]?.intValue, userImageURL: userDictionary?["image_url"]?.stringValue, userName: userDictionary?["name"]?.stringValue, comment: review["text"]?.stringValue, commentDate: commentDate, commentPageURL: review["url"]?.stringValue)
self.comments.append(yelpComment)
}
print("Number of comments: \(self.comments.count)") //Prints: Number of comments: 3"
self.tableView.reloadData()
})
print("Number of comments: \(self.comments.count)") //This prints firt "Number of comments: 0"
}
getYelpComments(for:completionHandler:)
類方法負責從Yelp API中獲取JSON數據。令我驚訝的是,即使comments
實例數組正在通過向其添加新的YelpComment
對象而被更新,其count
在閉包內部和外部具有不同的值。爲什麼實例變量在閉包內有不同的值?
這些註釋應該顯示在表格視圖中。更令我困惑的是,當我在閉包中添加tableView.reloadData()
時,我得到一個index out of bounds for an empty array
錯誤,但是當我在閉合一側添加相同的代碼行:tableView.reloadData()
時,我沒有發生錯誤,comments.count
等於零。任何幫助將非常感激!
P.S.我不知道提及這是否會有所作爲,但data
是@escaping
。我也使用SwiftyJSON
和Alamofire
。
UPDATE:
我的表視圖數據源的方法是:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return super.tableView(tableView, numberOfRowsInSection: section)
} else {
return comments.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
return super.tableView(tableView, cellForRowAt: indexPath)
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: CustomCellTypeIdentifiers.YelpCommentCell, for: indexPath) as! YelpCommentCell
cell.configureYelpCell(with: comments[indexPath.row])
return cell
}
}
'getYelpComments'是一個異步調用。在cloure外部的打印語句在閉包中的代碼運行之前執行。發佈你的'cellforRow'和'noOfRowsInSection'方法,我認爲這些方法正在導致崩潰.. – Bilal
@Bilal更新我的問題與表視圖數據源方法。 –