首页 > 解决方案 > UICollectionView 在再次触发 reloadData() 时发现 nil

问题描述

当我从集合视图中删除所有实际数据并添加新数据时,传递错误Unexpectedly found nil ,同时在再次触发reloadData()时解包 Optional 值。这是弹出的代码。

func getAllProducts(){
    print("All products before getting again from the func: \(productsAll.count)")

    productsAll.removeAll()

    refProducts.observeSingleEvent(of: .value) { (snapshot) in
        guard let productsDic = snapshot.value as? [String:AnyObject] else {return}

        for(_, productSelected) in productsDic{
            guard let name = productSelected["name"] as? String else {return}
            guard let imageURLString = productSelected["image"] as? String else {return}
            guard let price = productSelected["price"] as? String else {return}
            guard let description = productSelected["description"] as? String else {return}

            guard let imgURL = URL(string: imageURLString) else {return}
            guard let data = try? Data(contentsOf: imgURL) else {return}
            guard let img = UIImage(data: data) else {return}

            let productData = Product(productImage: img, productName: name, productPrice: price, productDescription: description, productRecommended: false)

            self.productsAll.append(productData)
            print("We have \(self.productsAll.count) products in All products")



        }

        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }


    }
}

标签: iosswift

解决方案


推荐阅读