iphone - 如何强制 iCloud 与核心数据同步?

标签 iphone ios5 icloud

我正在使用 iCloud 和核心数据来同步我的应用程序的数据。

我尝试了一切,最后它完美地工作了。

但我有一个问题。

有什么方法可以让 iCloud 同步吗?

它在应用程序启动时同步,但在其他时间同步。看起来它是随机同步的。我自己找不到处理的方法。

有什么帮助吗?

谢谢。

最佳答案

我想出了如何强制核心数据存储同步到 iCloud。您只需“触摸”Ubiquity 文件系统中 Data 文件夹中的任何收据文件即可。下面的代码将执行此操作。要强制同步,请调用syncCloud 方法。对于它找到的每个“收据”文件,它会将文件修改时间戳更新为当前时间,本质上是对文件进行“触摸”。一旦发生这种情况,iCloud 将检查并同步 iCloud 中任何需要同步的核心数据文件。据我所知,当您选择“触发 iCloud 同步”选项时,模拟器或 Xcode 就是这样做的。

@property (strong, nonatomic) NSMetadataQuery  *query;

-(void) init
{
    self.query = [[NSMetadataQuery alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(didFinishMetadataQuery)
                                                 name: NSMetadataQueryDidFinishGatheringNotification
                                               object: self.query];
}

-(void) didFinishMetadataQuery
{
    // Query completed so mark it as completed
    [self.query stopQuery];

    // For each receipt, set the modification date to now to force an iCloud sync
    for(NSMetadataItem *item in self.query.results)
    {
        [[NSFileManager defaultManager] setAttributes: @{NSFileModificationDate:[NSDate date]}
                                         ofItemAtPath: [[item valueForAttribute: NSMetadataItemURLKey] path]
                                                error: nil];
    }
}

-(void) syncCloud
{
    // Look for files in the ubiquity container data folders
    [self.query setSearchScopes:@[NSMetadataQueryUbiquitousDataScope]];

    // Look for any files named "receipt*"
    [self.query setPredicate:[NSPredicate predicateWithFormat:@"%K like 'receipt*'", NSMetadataItemFSNameKey]];

    // Start the query on the main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        BOOL startedQuery = [self.query startQuery];
        if (!startedQuery)
        {
            NSLog(@"Failed to start query.\n");
            return;
        }
    });
}

关于iphone - 如何强制 iCloud 与核心数据同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11282229/

相关文章:

iphone - Objective C 中两种迭代方式的区别?

swift - Xcode 版本 11.5 CloudKit 无法在模拟器上运行

xcode - 是否有用于 iCloud 磁盘容量和使用情况的 API?

iphone - 旋转时如何检测 UIPickerView 中心行

iphone ios xcode 4.2 - EXC_BAD_ACCESS 信号

iphone - Objective-C 弧错误 : -fobjc-arc is not supported with fragile abi

ios - UIDocument中如何实现文件协调

iphone - iOS 应用程序因区域设置更改而崩溃

ios - 实现 didReceiveRemoteNotification 以在推送到来时显示新的 viewController

iphone - 旋转期间 UIScrollView 的 contentOffset