2017-09-25 109 views
0

的陣列當刷新頁面出現錯誤指數超出範圍的對象

fatal error: Index out of range

我可以通過刪除線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 
    } 

} 
+0

如果未包括,則可以將帖子添加到帖子數組中。您可以檢查posts數組內的帖子的id,以確保不重複。 – ridvankucuk

+0

如果您在'handleRefresh()'末尾的集合視圖中調用[reloadData()](https://developer.apple.com/documentation/uikit/uicollectionview/1618078-reloaddata),它仍然會中斷嗎? – JeremyP

+0

removeAll函數體在哪裏,你能分享嗎? – dip

回答

-1
if posts.count != 0 { 

cell.post =帖[indexPath.item] }

+0

我認爲這有效 – bennypalmer661

0

當前您正在更改posts變量的內容而不讓CollectionView知道其基礎內容已發生變化。

這意味着CollectionView例如可能仍然認爲有10個帖子,而有0個,因爲用戶剛刪除它們。

每當您更改posts變量的內容時,您需要讓CollectionView知道它。最簡單的方法是使用reloadData()。這將觸發整個視圖的重新加載。如果您想要更具體,您也可以只更新一個部分(reloadSection)或行(reloadRow)。

Apple Documentation on reloadData()