问题
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