My code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
@autoreleasepool {
// Now on a background thread
// Setup background task
__block UIBackgroundTaskIdentifier bgTask;
void (^finishBackgroundTask)(void) = ^(void) {
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
};
// Start background task
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:finishBackgroundTask];
// The method below migrates a core data database and takes ages
[MyClass migrateCoreDataStuff];
finishBackgroundTask();
}
});
The error I get is NSUnderlyingException = "Fatal error. The database at /var/mobile/Applications/55B83D5F-CCF5-438E-BECA-B97DB5505541/Documents/Blah.sqlite is corrupted. SQLite error code:11, 'database disk image is malformed'";
The migration error only occurs when the following are all true:
* migration is on a background thread
* migration is running as a UIBackgroundTask
* I’m running on the device, not a simulator
I’m running iOS 4.3.5, building for iOS 4.0.
Without seeing the contents of
migrateCoreDataStuff, it’s hard to see the exact problem. However, Core Data on non-main threads is a tricksy issue. Have a read of http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdConcurrency.html. You’ll probably need, at a minimum, a separate managed object context for the new thread.