Я использую глобальную очередь отправки для настройки iCloud Coredata в моем проекте. Есть странная проблема. Первоначальная настройка iCloud CoreData может занять очень много времени.
В течение этого длительного периода:
, если приложение продолжает работать в первых рядах, и пользователь может играть с пользовательским интерфейсом
гладко.
НО если приложение переходит в фоновый режим и снова возвращается на передний план, пользовательский интерфейс
зависает и иногда не может правильно настроить данные iCloud Core,
(некоторые данные не объединены).
Фоновый процесс с отправленной очередью попадает в основной поток, когда он зависает во втором сценарии?
Другая возможная причина: я использовал отдельный класс DataManager для обработки всех этих методов CoreData, и это обычный подкласс из NSObject.
В то время как пример кода Apple поместил все эти основные данные в AppDelegate. Может ли это быть причиной?
Я боролся с проблемой в течение трех дней. Пожалуйста, помогите мне. Большое спасибо.
> Scheduling for the process "Launch>> go background>> come forefront"">
- (NSPersistentStoreCoordinator *)cloud_persistentStoreCoordinator {
if (_cloud_persistentStoreCoordinator != nil) {
return _cloud_persistentStoreCoordinator;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *cloudURL = [fileManager URLForUbiquityContainerIdentifier:UBIQUITY_CONTAINER_URL];
if (!cloudURL) {
self.iCloudReady=NO;
self.iCloudCoreDataReady=YES;
DEBUGLog
return nil;
}
self.iCloudReady=YES;
_cloud_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
// prep the store path and bundle stuff here since NSBundle isn't totally thread safe
NSPersistentStoreCoordinator* psc = _cloud_persistentStoreCoordinator;
NSURL *storeUrl = [[self applicationLibraryDirectory] URLByAppendingPathComponent:@"cloud_accounts.sqlite"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL* coreDataCloudContentURL = [cloudURL URLByAppendingPathComponent:@"accounts_v1"];
// The API to turn on Core Data iCloud support here.
NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:@"com.moremore.cloudapp.keys", NSPersistentStoreUbiquitousContentNameKey, coreDataCloudContentURL, NSPersistentStoreUbiquitousContentURLKey, [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,nil];
NSError *error = nil;
[psc lock];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible
* The schema for the persistent store is incompatible with current managed object model
Check the error message to determine what the actual problem was.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
[psc unlock];
// tell the UI on the main thread we finally added the store and then
// post a custom notification to make your views do whatever they need to such as tell their
// NSFetchedResultsController to -performFetch again now there is a real store
dispatch_async(dispatch_get_main_queue(), ^{
//user userDefaults to mark this will only be run once
NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
if ([userDefault objectForKey:@"oldCloudAccountsmoved"]==nil) {
AppDelegate * appdelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
[appdelegate moveOld_Cloud_DatabasetoCoreData];
NSString * confirm=@"YES";
[userDefault setObject:confirm forKey:@"oldCloudAccountsmoved"];
[userDefault synchronize];
}
NSLog(@"asynchronously added persistent store!");
[[NSNotificationCenter defaultCenter] postNotificationName:@"coreData_iCloud_Ready" object:self userInfo:nil];
});
});
return _cloud_persistentStoreCoordinator;
}