【发布时间】:2015-06-21 16:39:16
【问题描述】:
我有一个使用 xCode 6.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% 的时间都有效。
我使用以下内容来更新 UI:
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)")
}
我真的在这里停滞不前。我只是不确定为什么它“通常”有效......
【问题讨论】:
-
您确定这些更改会丢失,还是可能需要很长时间才能完成? iCloud 是一种异步传输机制。有时数据传输可能需要几分钟时间。另外,您确定您不会意外保存在第二台设备上,从而覆盖更改吗?真正的考验是,如果两台设备最终显示相同的数字,并且您已经等待了足够长的时间。
-
我等了几分钟。我意识到苹果不保证及时性,但我等了很长时间。在某些情况下,某些数据仅未能传播到三个设备之一,因此两个设备保持同步。无法正确同步的并不总是同一台设备。它就像一个有损系统。