Как получить ошибку «Неустранимая ошибка: индекс вне диапазона» при получении данных из Firestore? - PullRequest
0 голосов
/ 09 октября 2019

Я получаю пользовательские данные из двух разных коллекций для разных ячеек. Я могу получить данные, но могу установить данные для одной ячейки

  override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1 + posts.count
    }


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "detailscell") as! DetailsCellInHomeScreen
            if let imageURL = currentUserImageUrl {
                cell.configCell(userImgUrl: imageURL)
                cell.shareBtn.addTarget(self, action: #selector(toCreatePost), for: .touchUpInside)
            }
            cell.set(details: details[indexPath.row])
            return cell
        }

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

        cell.btnComment.tag = indexPath.row
        cell.btnComment.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)

        cell.favoritebutton.tag = indexPath.row
        cell.favoritebutton.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
        cell.set(post: posts[indexPath.row - 1])
        return cell
    }

, получая ошибку в этой строке

cell.set(details: details[indexPath.row])

Ответы [ 3 ]

2 голосов
/ 09 октября 2019

Проблема с вашим кодом заключается в том, что вы возвращаете метод 1 + posts.count из numberOfRowsInSection:, как показано ниже.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1 + posts.count
}

, и вы не обрабатываете, когда ваш путь индекса достигнут на posts.count.

Решение

Таким образом, решение состоит в том, чтобы вернуть posts.count из numberOfRowsInSection: метод.

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return posts.count
}

ИЛИ вы можете обработатьэта фатальная ошибка в методе cellForRow:.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
       .
       .
       .

        //Handle fatal error here

        cell.set(details: details[indexPath.row])
        return cell
    }
  .
  .
  .

  //Handle fatal error here
    cell.set(post: posts[indexPath.row - 1])

    return cell
}
0 голосов
/ 09 октября 2019

Примите меры предосторожности и сделайте условные проверки как:

        if details.indices.contains(indexPath.row) {
            cell.set(details: details[indexPath.row])
        }
        if posts.indices.contains(indexPath.row - 1) {
            cell.set(post: posts[indexPath.row - 1])
        }

Кажется, ваши массивы не заполнены.

0 голосов
/ 09 октября 2019

Сбои происходят, когда ваш массив posts или details пуст.

Модифицируйте cellForRow функцию, подобную этой

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 && details.count > 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "detailscell") as! DetailsCellInHomeScreen
            if let imageURL = currentUserImageUrl {
                cell.configCell(userImgUrl: imageURL)
                cell.shareBtn.addTarget(self, action: #selector(toCreatePost), for: .touchUpInside)
            }
            cell.set(details: details[indexPath.row])
            return cell
        } else if posts.count > (indexPath.row - 1) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell

            cell.btnComment.tag = indexPath.row
            cell.btnComment.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)

            cell.favoritebutton.tag = indexPath.row
            cell.favoritebutton.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)
            cell.set(post: posts[indexPath.row - 1])
            return cell
        } else { 
            return UITableViewCell()
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...