索引超出范围的对象数组

时间:2017-09-25 07:55:48

标签: ios swift firebase

刷新页面时出现错误

  

致命错误:索引超出范围

我可以通过删除行posts.removeAll()来解决错误,但后来我得到了多个相同类型的单元格。

我无法在Stack Overflow的所有其他解决方案中为我的场景做任何事情

我将不胜感激任何帮助

import UIKit
import Firebase

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout, HomePostCellDelegate {

    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()


        collectionView?.register(HomePostCell.self, forCellWithReuseIdentifier: cellId)

        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
        collectionView?.refreshControl = refreshControl


        fetchAllPosts()
    }

    func handleUpdateFeed() {
        handleRefresh()
    }

    func handleRefresh() {
        print("Handling refresh..")
        posts.removeAll()
        fetchAllPosts()

    }

    fileprivate func fetchAllPosts() {
        fetchPosts()
        fetchFollowingUserIds()
    }

    fileprivate func fetchFollowingUserIds() {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        Database.database().reference().child("following").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in

            guard let userIdsDictionary = snapshot.value as? [String: Any] else { return }

            userIdsDictionary.forEach({ (key, value) in
                Database.fetchUserWithUID(uid: key, completion: { (user) in
                    self.fetchPostsWithUser(user: user)
                })
            })

        }) { (err) in
            print("Failed to fetch following user ids:", err)
        }
    }


    var posts = [Post]()
    fileprivate func fetchPosts() {
        guard let uid = Auth.auth().currentUser?.uid else { return }

        Database.fetchUserWithUID(uid: uid) { (user) in
            self.fetchPostsWithUser(user: user)
        }
    }

    fileprivate func fetchPostsWithUser(user: User) {
        let ref = Database.database().reference().child("posts").child(user.uid)
        ref.observeSingleEvent(of: .value, with: { (snapshot) in

            self.collectionView?.refreshControl?.endRefreshing()

            guard let dictionaries = snapshot.value as? [String: Any] else { return }

            dictionaries.forEach({ (key, value) in
                guard let dictionary = value as? [String: Any] else { return }

                var post = Post(user: user, dictionary: dictionary)
                post.id = key


                    self.posts.append(post)


            })

        }) { (err) in
            print(err)
        }
    }



    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {


        return CGSize(width: view.frame.width, height: 300)
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return posts.count
    }

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomePostCell

        cell.post = posts[indexPath.item]

        cell.delegate = self

        return cell
    }

}

2 个答案:

答案 0 :(得分:0)

if posts.count != 0 {

cell.post = posts [indexPath.item] }

答案 1 :(得分:0)

目前,您正在更改posts变量的内容,而不让CollectionView知道其基础内容已更改。

这意味着例如CollectionView可能仍然假设有10个帖子,而有0个帖子,因为用户刚刚删除了它们。

每当您更改posts变量的内容时,都需要让CollectionView了解它。最简单的方法是使用reloadData()。这将触发整个视图的重新加载。如果您想要更具体,您还可以只更新部分(reloadSection)或行(reloadRow)。

Apple Documentation on reloadData()