deneov
deneov

Reputation: 63

CollectionView Reloaddata - Fatal error: Index out of range

I add the data that I have drawn from Database to CollectionView. I am putting the data I have added as an array in the model array. I see the data inside Array in collectionView. Sometimes data is added smoothly but sometimes I get the error

"Thread 1: Fatal error: Index out of range"

. Sometimes while working sometimes why not? I think there is a problem with collectionView.reloadData ().

enter image description here

@IBOutlet weak var sonsuzCollec: UICollectionView!
var model = [[String]]()
var davetiyefilee = [String]()
var davetiyefilee2 = [String]()

extension denemeView: UICollectionViewDelegate, UICollectionViewDataSource,  UICollectionViewDelegateFlowLayout {
    if (collectionView == sonsuzCollec) {
        return model[section].count
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if (collectionView == sonsuzCollec) {
            return yeniDavKATIsımNew.count
        }
        return 0
    }
...
}

@objc func davetiyeCEK1() {
    if let baslik = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
        for review in baslik {
            if let soru_baslik = review["davetiyefilee"] as? String {
                let s = String(describing: soru_baslik)
                self.davetiyefilee.append(s)
            }
        }
        self.model.append(self.davetiyefilee)
        DispatchQueue.main.async { [weak self] in
            self?.sonsuzCollec?.reloadData() 
        }  
    }
}

@objc func davetiyeCEK2() {
    if let baslik = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
        for review in baslik {
            if let soru_baslik = review["davetiyefilee"] as? String {
                let s = String(describing: soru_baslik)
                self.davetiyefilee2.append(s)
            } 
        }
        self.model.append(self.davetiyefilee2)
        DispatchQueue.main.async { [weak self] in
            self?.sonsuzCollec?.reloadData()
        }
    }
}

Upvotes: 0

Views: 199

Answers (1)

Adem Özsayın
Adem Özsayın

Reputation: 247

i think it is beacuse of your model array's section item is empty. how many collection you are using? can you show more full code

or maybe another approch is in your numberofsection try this

if (collectionView == sonsuzCollec) {
        var numberofRows = 0
        if model[section].count > 0 {
            numberofRows = model[section].count
        } else {
             numberofRows = 0
        }
        return  numberofRows
    }

Upvotes: 1

Related Questions