的陣列當刷新頁面出現錯誤指數超出範圍的對象
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
}
}
如果未包括,則可以將帖子添加到帖子數組中。您可以檢查posts數組內的帖子的id,以確保不重複。 – ridvankucuk
如果您在'handleRefresh()'末尾的集合視圖中調用[reloadData()](https://developer.apple.com/documentation/uikit/uicollectionview/1618078-reloaddata),它仍然會中斷嗎? – JeremyP
removeAll函數體在哪裏,你能分享嗎? – dip