我有一个使用Xcode6.3.2用Swift编写的通用应用程序。现在很简单,当我按下一个按钮时,会生成一个随机数,然后使用CoreData存储。在我实现iCloud之前,这一切都是完美的。启用iCloud后,存储新的随机数并不总是传播到其他设备上。大部分时间都是这样,但并不总是这样。
我正在用iPad Air、iPhone 6 Plus和iPhone 4s进行测试
我使用以下三个通知观察员:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "persistentStoreDidChange", name: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "persistentStoreWillChange:", name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: managedContext.persistentStoreCoordinator)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveiCloudChanges:", name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: managedContext.persistentStoreCoordinator)

下面是第三个函数:
func receiveiCloudChanges(notification: NSNotification)
{
    println("iCloud changes have occured")
    dispatch_async(dispatch_get_main_queue())
        {
            self.activityIndicator.startAnimating()
            self.updateLabel.text = "iCloud changes have occured"

            self.managedContext.performBlockAndWait
                { () -> Void in
                    self.managedContext.mergeChangesFromContextDidSaveNotification(notification)
                }
            self.reloadTextViewAndTableView()
            self.activityIndicator.stopAnimating()
        }
}

在managedContext完成合并之前,我不会尝试更新UI,而是在主线程上执行所有操作。我真的很困惑为什么一个设备上的更改只在第二个或第三个设备上显示,大约90-95%的时间。
作为我尝试和错误的一部分,当我从我的测试设备中删除应用程序并重新安装时,有时会有一条消息说iCloud操作正在挂起,但不管我等待多长时间,一旦设备不同步,它们就会保持这种状态。即使当它们不同步时,如果我再加上一两个数字,它们仍然会传播到其他设备,但之后我总是会丢失更多的数据。它似乎有90%的时间是有效的。
我使用以下命令更新用户界面:
func reloadTextViewAndTableView()
{
    let allPeopleFetch = NSFetchRequest(entityName: "Person")
    var error : NSError?
    let result = managedContext.executeFetchRequest(allPeopleFetch, error: &error) as! [Person]?

    //Now reload the  textView by grabbing every person in the DB and appending it to the textView
    textView.text = ""
    allPeople = managedContext.executeFetchRequest(allPeopleFetch, error: &error) as! [Person]
    for dude in allPeople
    {
        textView.text = textView.text.stringByAppendingString(dude.name)
    }
    tableView.reloadData()
    println("allPeople.count = \(allPeople.count)")
}

我真的站在这里一动不动。我只是不知道为什么它“通常”工作。。。

最佳答案

因此,我仍然不确定CoreData如何或为什么会像上面描述的那样失去同步。但我发现,如果我很快地输入一个又一个新数字,那就是它通常出现的时候。
作为解决方法,我在UI中添加了一个按钮,允许用户通过使用以下选项重建NSPersistentStore来强制与iCloud重新同步。

NSPersistentStoreRebuildFromUbiquitousContentOption: true

我更希望商店一直与所有其他设备保持同步,但至少这样用户永远不会丢失数据。如果他们发现丢失了一条记录,他们知道自己是在另一台设备上输入的,那么他们所要做的就是点击resync按钮。

关于swift - iOS 8 Core Data iCloud同步一致性问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30966891/

10-12 00:25
查看更多