我的代碼運行時出現故障:在後臺線程核心的數據遷移作爲UIBackgroundTask
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();
}
});
我得到的錯誤是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'";
遷移錯誤,只有當以下都是真會發生: *遷移是在後臺線程 *遷移正在作爲UIBackgroundTask *我在設備上運行,而不是一個模擬器
我跑的iOS 4.3。 5,建設iOS 4.0。
哎呦......算出來了。除了主線程外,任何人都不應該在UIKit中調用anthing。在這種情況下,我開始後臺任務('[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:]'),從而從後臺線程傳遞我的UIApplication實例。哪個*不好*。 – diachedelic
這是更正的代碼: – diachedelic
__block UIBackgroundTaskIdentifier bgTask; void(^ finishBackgroundTask)(void)= ^(void){[UIApplication sharedApplication] endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }; bgTask = [[UIApplication的sharedApplication] beginBackgroundTaskWithExpirationHandler:finishBackgroundTask]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^ { @autoreleasepool { [MyClass的migrateCoreDataStuff]; dispatch_async(dispatch_get_main_queue(),finishBackgroundTask); } }); – diachedelic