我的代码:
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 , '数据库磁盘镜像格式错误'";
迁移错误只有在满足以下条件时才会发生: * 迁移在后台线程上 * 迁移作为 UIBackgroundTask 运行 * 我在设备上运行,而不是模拟器
我正在运行 iOS 4.3.5,为 iOS 4.0 构建。
最佳答案
没有看到 migrateCoreDataStuff
的内容,很难看出确切的问题所在。然而,非主线程上的核心数据是一个棘手的问题。阅读 http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdConcurrency.html .您可能至少需要为新线程提供一个单独的托管对象上下文。
关于objective-c - 作为 UIBackgroundTask 运行时,后台线程上的核心数据迁移失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9002421/