gpt4 book ai didi

ios - 'NSInternalInconsistencyException' 使用 Collection View Swift 3 插入项目

转载 作者:行者123 更新时间:2023-11-28 06:24:07 28 4
gpt4 key购买 nike

因此,我将 Realm 用作数据存储,我很确定我需要先向其添加内容,然后再在 Collection View 中的索引路径处插入项目。但我不断收到这个太熟悉的错误:

'NSInternalInconsistencyException', 原因:'试图将第 1 项插入第 -1 节,但更新后第 1 节中只有 1 个项'

这是我的模型:

final class Listing: Object {
dynamic var id = ""
dynamic var name = ""
dynamic var item = ""

}

这是我的符合 UICollectionView 数据源和委托(delegate)的 View Controller :

 override func viewDidLoad() {
super.viewDidLoad()

// MARK: - Get Listings!

queryListings()

// MARK: - Delegates

self.collectionView.delegate = self
self.collectionView.dataSource = self
}

// MARK: - Query Listings

func queryListings() {
let realm = try! Realm()

let everyListing = realm.objects(Listing.self)
let listingDates = everyArticle.sorted(byKeyPath: "created", ascending: false)

for listing in listingDates {
listing.append(listing)
self.collectionView.performBatchUpdates({
self.collectionView.insertItems(at: [IndexPath(item: self.listing.count, section: 1)])
}, completion: nil)
}
}

代表们:

 // MARK: UICollectionViewDataSource

func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ListingCollectionViewCell

cell.awakeFromNib()

return cell
}

我已经尝试了 self.listing.count 0、1、-1、+1 以及第 0、1、-1、+1 部分的每一种排列,引发的异常是相同的加上或减去部分和存在的项目。调用 reloadData() 也无济于事。

有人用 Collection View 解决这个问题吗?

最佳答案

已解决

使用 Realm 时,思维方式与我习惯的不同——您正在操纵影响表或集合的数据,而不是直接影响表或集合。听起来很明显,但是……无论如何,TiM 的回答是正确的。这是 Collection View 版本:

// MARK: - Observe Results Notifications

notificationToken = articles.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in

guard (self?.collectionView) != nil else { return }

// MARK: - Switch on State

switch changes {

case .initial:
self?.collectionView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
self?.collectionView.performBatchUpdates({
self?.collectionView.insertItems(at: insertions.map({ IndexPath(row: $0, section: 0)}))
self?.collectionView.deleteItems(at: deletions.map({ IndexPath(row: $0, section: 0)}))
self?.collectionView.reloadItems(at: modifications.map({ IndexPath(row: $0, section: 0)}))
}, completion: nil)
break
case .error(let error):
print(error.localizedDescription)
break
}
}

关于ios - 'NSInternalInconsistencyException' 使用 Collection View Swift 3 插入项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42500504/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com