首页 > 解决方案 > 错误消息:在隐式展开可选值时意外发现 nil?

问题描述

我一直在尝试使用情节提要从 UICollectionView 中的 JSON 文件填充数据。创建网点后,我将图像和标签连接到 UICollectionViewCell.swift,将 Collection View 连接到 UICollectionView。但是,我收到一个错误,

在隐式展开 Optional 值时意外发现 nil:文件 Music2/ViewController.swift,第 22 行。

下面第 22 行指向“collectionView.dataSoure = self

 override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self

    parseJson()

  } 

之后,我解析了我的 JSON 文件并在 pasreJson() 的末尾添加了一个“DispatchQueue.main.async”(不确定该部分)。这会造成问题吗?

//JSON

private func parseJson(){
    guard let path = Bundle.main.path(forResource: "data (1)", ofType: "json") else {
        return
    }
   
    
    let url = URL(fileURLWithPath: path)
    do{
        let jsonData = try Data(contentsOf: url)
    let userData = try JSONDecoder().decode(UserData.self, from: jsonData)

        
        albums = userData.albums
        playlists = userData.playlists
        

    }catch{
        print("error : \(error)")
    }
    DispatchQueue.main.async {
        self.collectionView.reloadData()
          }
       }
    }

这是我完整的视图控制器:

   class ViewController: UIViewController, UICollectionViewDataSource {


   @IBOutlet weak var collectionView : UICollectionView!


   //INSTANCE OF JSON DATA
   var albums = [Album]()
    var playlists = [Playlist]()

      override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self

    parseJson()

     }
    //UICollectionView protocols
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection 
     section: Int) -> Int {

    return albums.count
     }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: 
     IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", 
    for: indexPath) as! CollectionViewCell
    
    cell.Label.text = albums[indexPath.row].title.capitalized
   
    return cell
    }



//JSON
    private func parseJson(){
    guard let path = Bundle.main.path(forResource: "data (1)", ofType: "json") else {
        return
    }
   
    
    let url = URL(fileURLWithPath: path)
    do{
        let jsonData = try Data(contentsOf: url)
    let userData = try JSONDecoder().decode(UserData.self, from: jsonData)

        
        albums = userData.albums
        playlists = userData.playlists
        

    }catch{
        print("error : \(error)")
    }
    DispatchQueue.main.async {
        self.collectionView.reloadData()
          }
         }
      }

标签: jsonswiftuicollectionviewstoryboarduicollectionviewcell

解决方案


如果您在线上崩溃,collectionView.dataSource = self那么您没有将集合视图连接到情节提要中的视图控制器。打开你的故事板并从集合视图控制拖动到视图控制器。


推荐阅读