UICollectionView + NSFetchedResultsController in Swift 3

一世执手 提交于 2019-12-08 06:09:32

问题


In my current project I integrated a NSFetchedResultsController with a UICollectionView which works fine. Currently I try to upgrade the project to Swift 3 and Xcode 8 which causes the following error message

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread.

I'm using a BlockOperation array to queue up the changes to the UICollectionView. Here is an example of how I insert a new item.

self.blockOperations.append(BlockOperation(block: {
   collectionView?.insertItems( at: [newIndexPath!])
}))

This is my current implementation of controllerDidChangeContent

var blockOperations = [BlockOperation]()

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    if self.shouldReloadCollectionView {
        self.collectionView.reloadData()
    }
    self.collectionView?.performBatchUpdates({    
        for operation in self.blockOperations {
            OperationQueue.current?.addOperation(operation)
        }
        }, completion: { (completed) in
            print(completed)
    })
}

Has anyone implemented NSFetchedResultsController with a UICollectionView in Swift 3 an can help me with this?


回答1:


Thank you Pawel, your Gist was very helpful. I forked it and updated it to fully support Swift 3 and iOS10. Since it doesn't solved the problem with updating the UICollectionView from a background thread.

The error is caused by updating the UICollectionView from a background thread.

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread.

To get a combination of NSFetchedResultsController and UICollectionView working you have to wrap every update of the collectionView object inside

DispatchQueue.main.async {
    // i.e. insertion of new items                          
    this.collectionView!.insertItems(at: [newIndexPath!])
}

Here is a link to the full updated Gist



来源:https://stackoverflow.com/questions/40024166/uicollectionview-nsfetchedresultscontroller-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!