Fix: App Crashes Starting Background Thread in iOS

Written by

in

Quick answer: performSelectorInBackground requires you to create your own autorelease pool — without it the app crashes. Wrap the method body in @autoreleasepool or, better, replace it with dispatch_async to a global queue and dispatch back to the main queue to update UI.

Why this happens

performSelectorInBackground:withObject: and detachNewThreadSelector:toTarget:withObject: create a new NSThread for you, but that thread starts with almost no setup. Unlike the main thread, it has no autorelease pool, no run loop, and no automatic memory management context. If your method creates any autoreleased objects — which almost every Foundation and UIKit call does — they have nowhere to go and the app crashes, often with an empty stack trace and autorelease pool page corrupted or object autoreleased with no pool in place in the console.

The crash only appears on the background thread. On the main thread the same getResultSetFromDB: code works because the main thread’s autorelease pool is set up by UIKit at launch. Moving the SQLite fetch to a background thread exposes the missing pool immediately.

There is a second problem in the posted method. NSMutableArray *filteredDocids = toProceessDocids; does not copy the array, it just points to the same object. Later [filteredDocids release]; over-releases the original docids array that the caller still owns. On the main thread this might survive by luck; on a background thread with no pool it crashes faster. You also must never touch UIKit from that background thread — all UI updates have to be dispatched back to the main thread.

How to fix it

1. Add an autorelease pool if you keep performSelectorInBackground

If you must keep the old API, the selector you run is responsible for its own pool. Wrap all work in @autoreleasepool.

This is the minimal fix that stops the immediate crash:

- (void)getResultSetFromDB:(NSMutableArray *)toProcessDocids {
    @autoreleasepool {
        SpotMain *mirror = [[SpotMain alloc] init];
        NSMutableArray *filteredDocids = toProcessDocids;

        if (![gMediaBucket isEqualToString:@""]) {
            filteredDocids = [mirror FetchDocIdsForMediaBucketWithDocID:filteredDocids mBucket:gMediaBucket numRes:-1];
        }
        if (![gMediaType isEqualToString:@""]) {
            filteredDocids = [mirror FetchDocIdsForMediaType:filteredDocids mediaType:gMediaType numRes:-1];
        }
        if (![gPlatform isEqualToString:@""]) {
            filteredDocids = [mirror FetchDocIdsForPlatformID:filteredDocids platformId:@"1" numRes:-1];
        }

        self.resultSet = [mirror FetchObjectFromDocid:filteredDocids];
        // Do NOT release filteredDocids if it may point to toProcessDocids
        // Only release objects you alloc/init/copy/new
        [mirror release];

        [self performSelectorOnMainThread:@selector(showResults) withObject:nil waitUntilDone:NO];
    }
}

Call it as before:

[self performSelectorInBackground:@selector(getResultSetFromDB:) withObject:docids];

Do not call [filteredDocids release] unless you created that specific instance with alloc, copy, or mutableCopy. Assigning filteredDocids = toProcessDocids does not transfer ownership.

This fixes the crash, but Apple considers this API legacy. You still have to manage thread lifetime yourself and you get no queue priority, cancellation, or QoS.

2. Use Grand Central Dispatch (recommended)

GCD creates and reuses threads for you and every block dispatched to a global queue already has an autorelease pool. It is less code, safer, and more efficient.

Objective-C pattern for a SQLite fetch + UI update:

#import <dispatch/dispatch.h>

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    // Background work - no UI here
    // You can call your existing method, or inline the fetch
    [self getResultSetFromDB:docids];

    // Or do the work directly and hop back to main:
    // NSArray *results = [self fetchAndProcess:docids];
    // dispatch_async(dispatch_get_main_queue(), ^{
    //     self.resultSet = results;
    //     [self showResults];
    // });
});

If getResultSetFromDB: already does performSelectorOnMainThread: at the end, you can keep it. A cleaner version does both hops in one place:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    SpotMain *mirror = [[SpotMain alloc] init];
    NSMutableArray *filtered = docids;
    if (![gMediaBucket isEqualToString:@""]) {
        filtered = [mirror FetchDocIdsForMediaBucketWithDocID:filtered mBucket:gMediaBucket numRes:-1];
    }
    // ... other filters ...
    NSArray *result = [mirror FetchObjectFromDocid:filtered];
    [mirror release];

    dispatch_sync(dispatch_get_main_queue(), ^{
        self.resultSet = result;
        [self showResults];
    });
});

Use dispatch_async for the main queue hop if showResults does not need to block the background work. Use dispatch_sync only when you need the background block to wait until the UI update finishes.

Swift equivalent:

import Dispatch

DispatchQueue.global(qos: .userInitiated).async {
    let results = self.fetchFromDB(docids: docids) // your SQLite + processing
    DispatchQueue.main.async {
        self.resultSet = results
        self.showResults()
    }
}

qos: .userInitiated is appropriate for work the user is waiting for after tapping a button. Use .utility for longer imports or prefetching.

3. Use modern Swift Concurrency if your target is iOS 13+

If you are writing Swift today, Task and MainActor replace manual GCD hops and make the main-thread requirement explicit:

Task.detached(priority: .userInitiated) {
    let results = await self.fetchFromDB(docids: docids)
    await MainActor.run {
        self.resultSet = results
        self.showResults()
    }
}

Task.detached runs off the main actor. MainActor.run guarantees showResults() runs on the main thread. You get the same autorelease pool handling automatically and the compiler will warn you if you try to touch @MainActor UI state from the background.

4. Fix the memory management bug

Even after you switch to GCD, remove the incorrect release:

// Wrong
NSMutableArray *filteredDocids = toProceessDocids;
// ...
[filteredDocids release]; // over-release if no filter ran

// Correct - only release what you own
NSMutableArray *filteredDocids = toProceessDocids;
NSMutableArray *temp = nil;
if (![gMediaBucket isEqualToString:@""]) {
    temp = [mirror FetchDocIdsForMediaBucketWithDocID:filteredDocids mBucket:gMediaBucket numRes:-1];
    // if Fetch... returns a retained object, you own temp and must release it later
    // if it returns autoreleased, do not release
    filteredDocids = temp;
}

If your FetchDocIds... methods return autoreleased arrays (the convention unless the name contains alloc, new, copy, or mutableCopy), do not release them at all under ARC, and do not call release manually. If the project still uses Manual Retain Release, audit each method’s naming and return ownership.

Also make sure SQLite access is thread-safe. Either open a separate database connection per queue/thread or serialize all DB access on a single serial queue. Sharing one sqlite3* handle across threads without serialization will corrupt results or crash.

How to prevent it

  • Prefer DispatchQueue.global().async or Swift Task over performSelectorInBackground and NSThread for one-off background work. GCD provides the autorelease pool and QoS for you.
  • Always dispatch UI work back to the main queue with DispatchQueue.main.async or MainActor.run. Never update UILabel, UITableView, or other UIKit objects from a background queue.
  • Wrap any manual NSThread entry point in @autoreleasepool { ... } as the first line.
  • Do not release objects you did not alloc/copy/new/retain. With ARC, remove manual release calls entirely.
  • Give SQLite its own serial queue: let dbQueue = DispatchQueue(label: "com.app.db") and perform all sqlite3_* calls on that queue.

FAQ

Why does performSelectorInBackground crash but the same code works on the main thread?

The main thread is created by UIKit with an autorelease pool and run loop already installed. A thread created with performSelectorInBackground starts bare. Any autoreleased object created without a pool triggers autorelease pool page corrupted and the app terminates. Adding @autoreleasepool or switching to GCD, which installs a pool automatically, fixes it.

Should I use dispatch_sync or dispatch_async to update the UI?

Use dispatch_async(dispatch_get_main_queue(), ^{ ... }) in most cases. It enqueues the UI update and lets the background work continue or finish. Use dispatch_sync only when the background task must wait for the UI update to complete before continuing, and never call dispatch_sync to the main queue from the main thread itself or you will deadlock.

Is GCD better than performSelectorInBackground for SQLite fetches?

Yes. GCD reuses a pool of threads, sets up autorelease pools, respects QoS, and requires less boilerplate. performSelectorInBackground spawns a new thread each time and leaves pool and run-loop setup to you. For database work, dispatch to a global queue with qos: .userInitiated and hop back to DispatchQueue.main for showResults.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.