[英]iOS with Swift: App crashes on UITableView scroll down event
我正在用Swift編寫一個iOS應用,該應用將來自API的數據放入TableView中。 目標是用戶可以向下滾動博客帖子的連續列表。 發生的情況是,數據可以很好地填充第一個屏幕的單元格數量,但是當用戶向下滾動時,應用程序由於單元格屬性之一而崩潰, cellImageView
變為nil
並且被解包(因為在單元格類的代碼中指定了強制解包) ):
class BlogPostEntryCell: UITableViewCell {
//MARK: Properites
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var bodyTextView: UITextView!
@IBOutlet weak var initialsImageView: UIImageView!
}
這是導致崩潰的代碼:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCell
apiCaller.getAPIDataThroughAsyncCall(id: nextCell, entry: { cellContent in
DispatchQueue.main.async(execute: {
cell.cellLabel.text = cellContent.labelText
cell.cellTextView.text = cellContent.textViewText
// App crashes at the below line
cell.initialsImageView = self.createPicture(initials: cellContent.pictureText)
})
})
nextCell += 1
return cell
}
有趣的是,如果這樣做:
cell.cellLabel?.text = cellContent.labelText
cell.cellTextView?.text = cellContent.textViewText
// App does NOT crash at the below line
cell.initialsImageView? = self.createPicture(initials: cellContent.pictureText)
,應用程序不會崩潰,但數據會隨着用戶滾動而重復一遍又一遍。
我在這里嘗試過解決類似問題的解決方案: 為什么在快速滾動tableview之后,從coredata返回的數據為何變為nil? ,但這沒有用。 但是,我確實認為這與異步API調用有關。
我認為可能的解決方案可能包括在生成單元之前填充一組API數據,但是在重新考慮代碼的體系結構之前,我希望對此問題的來源有所了解。
您需要在viewDidLoad
進行API調用,以了解其中有多少個元素並將其ID記錄在數組中。 然后在您的cellForRow
函數中,您可以通過這種方式獲取ID
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCell
apiCaller.getAPIDataThroughAsyncCall(id: array[indexPath.row], entry: { cellContent in
DispatchQueue.main.async(execute: {
...
})
})
return cell
}
您的nextCell無法工作的原因是,每次當表視圖試圖顯示當前不在屏幕上的單元格時,都會調用此cellForRow
函數。 假設您知道您有10個元素,並且屏幕上只能顯示5個元素。 當您滾動到底部時,您的nextCell將變為10,並且一切正常。 但是現在當您向上滾動時,表格視圖必須再次准備前5個。 因此,現在您的nextCell變為15,您在API調用中沒有相應的元素。
不好的做法是在cellForRowAt indexPath:IndexPath中調用任何API,如您所見,它會導致崩潰,請看一下MVVM。 這就像贏得一場戰爭而不必參加戰斗一樣,我指的是您在cellForRowAt indexPath中調用API的此實例:IndexPath並且出口未初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.