启用 iCloud 时 iOS 应用程序在首次启动时冻结

2024-04-11

我在 iOS 应用程序中启用了 iCloud,并且在首次启动应用程序时,当我按下应用程序中的任何视图时,应用程序会冻结大约 5 秒。我跟着this http://timroadley.com/2012/04/03/core-data-in-icloud/在我的应用程序中启用 iCloud 并使用核心数据同步数据的教程。在添加iCloud同步之前我没有这个问题。这只发生在第一次启动时,而不是在应用程序的其他启动时发生。 iCloud 同步确实发生。问题是应用程序冻结。

这是管理我的应用程序委托中的同步的代码。

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    /*if (persistentStoreCoordinator == nil) {
        NSURL *storeURL = [NSURL fileURLWithPath:[self dataStorePath]];

        persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];

        NSError *error;
        if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
            NSLog(@"Error adding persistent store %@, %@", error, [error userInfo]);
            abort();
        }
    }
    return persistentStoreCoordinator;*/

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    if ((persistentStoreCoordinator != nil)) {
        return persistentStoreCoordinator;
    }

    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSPersistentStoreCoordinator *psc = persistentStoreCoordinator;

    // Set up iCloud in another thread:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // ** Note: if you adapt this code for your own use, you MUST change this variable:
        NSString *iCloudEnabledAppID = @"48S27G4A2S.com.maxned.iDownloadBlog";

        // ** Note: if you adapt this code for your own use, you should change this variable:
        NSString *dataFileName = @"DataStore.sqlite";

        // ** Note: For basic usage you shouldn't need to change anything else

        NSString *iCloudDataDirectoryName = @"Data.nosync";
        NSString *iCloudLogsDirectoryName = @"Logs";
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *localStore = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:dataFileName];
        NSURL *iCloud = [fileManager URLForUbiquityContainerIdentifier:nil];

        if (iCloud)
        {
            //NSLog(@"iCloud is working");

            NSURL *iCloudLogsPath = [NSURL fileURLWithPath:[[iCloud path] stringByAppendingPathComponent:iCloudLogsDirectoryName]];

            /*NSLog(@"iCloudEnabledAppID = %@",iCloudEnabledAppID);
            NSLog(@"dataFileName = %@", dataFileName);
            NSLog(@"iCloudDataDirectoryName = %@", iCloudDataDirectoryName);
            NSLog(@"iCloudLogsDirectoryName = %@", iCloudLogsDirectoryName);
            NSLog(@"iCloud = %@", iCloud);
            NSLog(@"iCloudLogsPath = %@", iCloudLogsPath);*/

            if ([fileManager fileExistsAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]] == NO) {
                NSError *fileSystemError;
                [fileManager createDirectoryAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]
                       withIntermediateDirectories:YES
                                        attributes:nil
                                             error:&fileSystemError];

                if (fileSystemError != nil) {
                    NSLog(@"Error creating database directory %@", fileSystemError);
                }
            }

            NSString *iCloudData = [[[iCloud path]
                                     stringByAppendingPathComponent:iCloudDataDirectoryName]
                                    stringByAppendingPathComponent:dataFileName];

            //NSLog(@"iCloudData = %@", iCloudData);

            NSMutableDictionary *options = [NSMutableDictionary dictionary];
            [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
            [options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
            [options setObject:iCloudEnabledAppID forKey:NSPersistentStoreUbiquitousContentNameKey];
            [options setObject:iCloudLogsPath forKey:NSPersistentStoreUbiquitousContentURLKey];

            [psc lock];

            [psc addPersistentStoreWithType:NSSQLiteStoreType
                configuration:nil
                URL:[NSURL fileURLWithPath:iCloudData]
                options:options
                error:nil];

            [psc unlock];

        } else {

            NSLog(@"iCloud is NOT working - using a local store");
            NSMutableDictionary *options = [NSMutableDictionary dictionary];
            [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
            [options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

            [psc lock];

            [psc addPersistentStoreWithType:NSSQLiteStoreType
                configuration:nil
                URL:localStore
                options:options
                error:nil];

            [psc unlock];

        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SomethingChanged" object:self userInfo:nil];
        });
    });

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    return persistentStoreCoordinator;
}

/*- (NSManagedObjectContext *)managedObjectContext
{
    if (managedObjectContext == nil) {
        NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
        if (coordinator != nil) {
            managedObjectContext = [[NSManagedObjectContext alloc] init];
            [managedObjectContext setPersistentStoreCoordinator:coordinator];
        }
    }
    return managedObjectContext;
}*/

- (NSManagedObjectContext *)managedObjectContext
{
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator != nil) {
        NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

        [moc performBlockAndWait:^{
            [moc setPersistentStoreCoordinator: coordinator];
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
        }];
        managedObjectContext = moc;
    }

    return managedObjectContext;
}

- (void)mergeChangesFrom_iCloud:(NSNotification *)notification
{
    //NSLog(@"Merging in changes from iCloud...");

    NSManagedObjectContext* moc = [self managedObjectContext];

    [moc performBlock:^{

        [moc mergeChangesFromContextDidSaveNotification:notification];

        NSNotification* refreshNotification = [NSNotification notificationWithName:@"SomethingChanged"
            object:self
            userInfo:[notification userInfo]];

        [[NSNotificationCenter defaultCenter] postNotification:refreshNotification];
    }];
}

为了解决这个问题,我更改了代码以将其放入另一个线程中。

dispatch_queue_t mainQueue = dispatch_get_main_queue();
        dispatch_async(mainQueue, ^{

            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSURL *localStore = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:dataFileName];
            NSURL *iCloud = [fileManager URLForUbiquityContainerIdentifier:nil];

            if (iCloud)
            {
                //NSLog(@"iCloud is working");

                NSURL *iCloudLogsPath = [NSURL fileURLWithPath:[[iCloud path] stringByAppendingPathComponent:iCloudLogsDirectoryName]];

                /*NSLog(@"iCloudEnabledAppID = %@",iCloudEnabledAppID);
                 NSLog(@"dataFileName = %@", dataFileName);
                 NSLog(@"iCloudDataDirectoryName = %@", iCloudDataDirectoryName);
                 NSLog(@"iCloudLogsDirectoryName = %@", iCloudLogsDirectoryName);
                 NSLog(@"iCloud = %@", iCloud);
                 NSLog(@"iCloudLogsPath = %@", iCloudLogsPath);*/

                if ([fileManager fileExistsAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]] == NO) {
                    NSError *fileSystemError;
                    [fileManager createDirectoryAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]
                           withIntermediateDirectories:YES
                                            attributes:nil
                                                 error:&fileSystemError];

                    if (fileSystemError != nil) {
                        NSLog(@"Error creating database directory %@", fileSystemError);
                    }
                }

                NSString *iCloudData = [[[iCloud path]
                                         stringByAppendingPathComponent:iCloudDataDirectoryName]
                                        stringByAppendingPathComponent:dataFileName];

                //NSLog(@"iCloudData = %@", iCloudData);

                NSMutableDictionary *options = [NSMutableDictionary dictionary];
                [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
                [options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
                [options setObject:iCloudEnabledAppID forKey:NSPersistentStoreUbiquitousContentNameKey];
                [options setObject:iCloudLogsPath forKey:NSPersistentStoreUbiquitousContentURLKey];

                [psc lock];

                [psc addPersistentStoreWithType:NSSQLiteStoreType
                                  configuration:nil
                                            URL:[NSURL fileURLWithPath:iCloudData]
                                        options:options
                                          error:nil];

                [psc unlock];

            } else {

                NSLog(@"iCloud is NOT working - using a local store");
                NSMutableDictionary *options = [NSMutableDictionary dictionary];
                [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
                [options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

                [psc lock];

                [psc addPersistentStoreWithType:NSSQLiteStoreType
                                  configuration:nil
                                            URL:localStore
                                        options:options
                                          error:nil];

                [psc unlock];
            }
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

启用 iCloud 时 iOS 应用程序在首次启动时冻结 的相关文章

随机推荐

  • 默认情况下,PHPUnit 模拟对象从未期望过

    如果没有正式定义的期望 有没有办法告诉 phpunit 模拟对象永远不要期望方法调用 在我看来 不要对每种方法都抱有期望是没有道理的 所以 phpunit 没有任何功能 仅当您想完全确保某些方法不会被调用时 才应使用 从不 期望 无论如何
  • 查找每个逗号后的第二个空格

    This is a follow up to this question Concatenate previous and latter words to a word that match a condition in R https s
  • 如何更新猫鼬中的特定字段?

    我有一个数据集是 var JobSchema Schema candidates user type Schema Types ObjectId ref User status type String default In Progress
  • 如何使用私钥对字符串进行签名

    如何使用以下方式获取字符串的签名SHA1withRSA如果我已经拥有私钥byte or String 我想你所说的是你事先知道密钥对并且想用它来签名 验证 请看下面的代码 import java security KeyPair impor
  • 针对 SSE2 之前的处理器的 Java 运行时如何实现浮点基本运算?

    针对没有 SSE2 的 Intel 处理器的 Java 运行时如何处理浮点非规格化 当strictfp is set 即使 387 FPU 设置为 53 位精度 它也会保持超大的指数范围 强制检测每个中间结果的下溢 溢出 以及 使得很难避免
  • Python JSON AttributeError:“str”对象没有属性“read”

    我是 Python 初学者 Python 3 7 6 import json fil numbers json num with open fil r as file for obj in file num append json load
  • 如何用一个命令停止 mongo DB

    我需要能够在 cli 上启动 停止 MongoDB 开始非常简单 mongod 但要停止 mongo DB 我需要先运行 open mongo shell 然后键入两个命令 蒙戈 使用管理员 db shutdownServer 所以我不知道
  • shark不显示源代码

    我们正在尝试在 iPhone 应用程序上运行 shark 然而 在分析的样本中 它没有列出我们的任何应用程序功能 所有列出的都是库 当我们单击其中任何一个时 汇编代码都是可见的 大多数网站在构建应用程序时都会提到 生成调试符号 选项 我也找
  • 包括使用 Lambda 表达式

    在基于字符串的重载中Include我们指定包含一个集合 然后简单地通过以正确的顺序指定相关导航属性来包含下一层的引用 query Include Level1Collection Level2Reference 但是为什么当使用重载时Inc
  • Android 的自定义类加载器?

    我正在编写一个仪器库 我想在桌面和移动设备 Android 上使用它 它的功能是 公开一个带有单个参数的 main 即目标类的 main 安装一个类加载器 在加载所有类时拦截它们并对其进行检测 Like so Expects args 0
  • Electron打包后不支持ES6

    我正在使用各种ES6语法 http es6 features org 例如importETC React https reactjs org code JSX https reactjs org docs introducing jsx h
  • NEHotspotConfigurationManager 收到此警报:“无法加入网络<网络名称>”,而错误为零

    所以我试图通过关闭器监视连接状态 func reconnect success escaping gt Void failure escaping gt Void let manager NEHotspotConfigurationMana
  • 有没有办法摆脱 git status 中的帮助消息?

    Changes not staged for commit use git add
  • 如何从 Instagram API 获取访问令牌

    我一直在关注 Instagram 的基本指南https developers facebook com docs instagram basic display api guides getting access tokens and pe
  • 删除 t-sql 中所有大表的最佳方法是什么?

    我们遇到了一个有点奇怪的情况 基本上 我们的一个数据库中有两个表 其中包含大量我们不需要或不关心的日志信息 部分原因是我们的磁盘空间不足 我正在尝试清理表 但这需要很长时间 在周末运行后仍然有 57 000 000 多条记录 而这只是第一个
  • PageView 内的 InteractiveViewer

    我正在创建一个包含图像列表的 PageView 并且我想向每个图像添加 InteractiveViewer 以便可以调整其大小以查看详细信息 这是我写的 PageView builder dragStartBehavior DragStar
  • 将 numpy 数组转换为十六进制字节数组

    我想在 python 2 7 中将 numpy 数组转换为字节串 比如说我的 numpy 数组a是一个简单的2x2数组 看起来像这样 1 10 16 255 我的问题是 如何将此数组转换为字节字符串或字节数组 输出如下 x01 x0A x1
  • 如何使用webpack导入静态url

    如何使用 webpack 导入静态 url index js import http google com myscript js 确实不清楚你想做什么 但总的来说你有几个选择 预先下载脚本或通过 NPM 安装 这可能是处理外部依赖关系的首
  • Ruby on Rails robots.txt 文件夹

    我即将启动 Ruby on Rails 应用程序 作为最后一个任务 我想设置机器人 txt文件 我找不到有关如何为 Rails 应用程序正确编写路径的信息 起始路径是否始终是 Ruby on Rails 应用程序或应用程序文件夹的根路径 那
  • 启用 iCloud 时 iOS 应用程序在首次启动时冻结

    我在 iOS 应用程序中启用了 iCloud 并且在首次启动应用程序时 当我按下应用程序中的任何视图时 应用程序会冻结大约 5 秒 我跟着this http timroadley com 2012 04 03 core data in ic