我正在构建一个用户可以阅读文章的应用程序。每篇文章都由作者撰写,因此,在文章视图中,当用户单击作者的个人资料图片时,它会导航到作者的个人资料视图。
在作者简介视图中,有一个“关注”按钮,在同一视图中,还有作者的统计信息(例如,他/她写了多少篇文章,他们有多少关注者等)。与此非常接近的东西:
当作者个人资料视图加载时,一切正常。但是一旦用户触摸“关注”按钮,应用程序就会崩溃并出现以下错误:
由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“部分标识符计数与数据源计数不匹配。这很可能是由于标识符的散列问题。
这些是我遵循的步骤:
- 作者个人资料视图中的用户
- 用户看到“关注”按钮和显示有多少用户关注作者的统计数据
- 假设作者有 10 个关注者。用户点击“关注”按钮
- 在幕后,我进入 Firebase,获取作者,然后使用 .observeSingleEvent() 和 setValue() 将用户 ID 添加到字符串数组中:
- 然后我使用 Firebase 的.observe()方法读取数据,从“关注”->“关注”更新按钮状态,并从“10”->“11”增加关注者的值
编辑:代码部分:
enum AuthorProfileSection {
case details
case stats
case articles
}
数据源创建:
func configureDataSource() -> UICollectionViewDiffableDataSource<AuthorProfileSection, AnyHashable> {
let dataSource = UICollectionViewDiffableDataSource<AuthorProfileSection, AnyHashable>(collectionView: collectionView) { (collectionView, indexPath, object) -> UICollectionViewCell? in
if let object = object as? Author {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AuthorDetailsCell.reuseIdentifier, for: indexPath) as! AuthorDetailsCell
cell.configure(with: object)
return cell
}
if let object = object as? AuthorStatsForAuthorProfile {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AuthorStatCell.reuseIdentifier, for: indexPath) as! AuthorStatCell
cell.configure(with: object)
return cell
}
if let object = object as? Article {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AuthorArticleCell.reuseIdentifier, for: indexPath) as! AuthorArticleCell
cell.configure(with: object)
return cell
}
return nil
}
return dataSource
}
更新快照
fileprivate func updateSnapshot(animated: Bool = false) {
guard let authorUID = authorUID else { return }
Firebase.Database.database().fetchSelectedAuthorProfileData( authorUID: authorUID, fromArticleUID: self.articleUID) { authorProfileSection in
var snapshot = self.dataSource.snapshot()
// sections
snapshot.appendSections([.details, .stats, .articles])
snapshot.appendItems([authorProfileSection.details], toSection: .details)
snapshot.appendItems(authorProfileSection.stats ?? [], toSection: .stats)
snapshot.appendItems(authorProfileSection.articles ?? [], toSection: .articles)
self.dataSource.apply(snapshot, animatingDifferences: animated)
}
}
和细胞:
class AuthorStatCell: UICollectionViewCell, SelfConfiguringCell {
typealias someType = AuthorStatsForAuthorProfile
static var reuseIdentifier = "AuthorStatCell"
override init(frame: CGRect) {
super.init(frame: frame)
buildUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(with data: AuthorStatsForAuthorProfile) {
print(data)
}
fileprivate func buildUI() {
backgroundColor = UIColor(red: 0.20, green: 0.83, blue: 0.60, alpha: 1.00)
layer.cornerRadius = 15
}
}
这就是结果(如果我触摸“关注”按钮,红色部分会发生变化):
这是应用程序崩溃的地方。知道为什么吗?