iOS Swift: Fix 'EXC_BAD_ACCESS' Crash on Background Thread UI Update

Updating UIKit from a background thread causes random crashes that are notoriously hard to reproduce. Here's the fix.

swift ios threading crash fix

The Problem


Your app crashes with EXC_BAD_ACCESS or Main Thread Checker warnings.


The Fix


Always dispatch UI updates to the main thread:


DispatchQueue.main.async {
    self.tableView.reloadData()
}

With async/await (Swift 5.5+)


Use @MainActor to guarantee UI work runs on the main thread:


@MainActor
func loadData() async {
    let posts = await fetchPostsFromAPI()
    self.tableView.reloadData()
}