簡體   English   中英

我如何修復,在我的代碼中解包 Optional 值時意外發現 nil

[英]How do I fix ,Unexpectedly found nil while unwrapping an Optional value, in my code

我的代碼有問題,一切正常,然后我開始收到此錯誤

“線程 1:致命錯誤:在展開可選值時意外發現 nil”

當我讓我的單元格變量成為可重用單元格時,就會發生錯誤。

這是我的代碼,錯誤發生在聲明 let cell 的第 3 行。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let song = songs[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell") as! SongCell
    cell.setSong(song: song)
    return cell
}

更新:我已經修復了致命錯誤,但我現在得到了

“線程 1:信號 SIGABRT”

添加此代碼以設置表視圖數據源和委托時發生錯誤。

override func viewDidLoad() {
            super.viewDidLoad()
            songs = createArray()
            playlists = createArray2()
            tableView.dataSource = self
            tableView.delegate = self
            tableView2.dataSource = self    //Adding this causes app to crash
            tableView2.delegate = self  //Adding this causes the app to crash

        // Do any additional setup after loading the view, typically from a nib.
    }  

每當我刪除此代碼時,應用程序都會啟動,但表格視圖中沒有顯示任何單元格。

您缺少dequeueReusableCell的第二個參數

let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath) as! SongCell

確保注冊一個筆尖或類

tableView.register(UINib(nibName: "NibSongCell", bundle: nil), forCellReuseIdentifier: "SongCell")

或者

// if using a custom cell, replace UITableViewCell.self with that class
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SongCell")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM