作为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构建。

如果看不到migrateCoreDataStuff的内容,就很难看到确切的问题。然而,非主线程上的核心数据是一个棘手的问题。阅读http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdConcurrency.html.您可能至少需要为新线程提供一个单独的托管对象上下文。

最新更新