Reputation: 45
I have a crash when trying to reload collectionView inside the method update() which marked as @MainActor. "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread"
I know, that you should update the UI from main thread only. Using GCD it works
private func update() {
DispatchQueue.main.async {
collectionView.reloadData()
}
}
I thought that if you mark you method with @MainActor in async/await world, then this function will be executed in the main thread automatically. But it crashes.
extension PhotosCollectionViewController: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
update()
}
@MainActor private func update() {
collectionView.reloadData()
}
}
What am I missing?
Upvotes: 1
Views: 783
Reputation: 1218
@MainActor
only works when using Swift concurrency and ensures that when you are in an async context calling a @MainActor
annotated function is executed on the main thread (actually the actor's executor which in this case is always the main queue).
In your example you call the function in a synchronous context which uses the same thread it was called from (as always).
Upvotes: 1