【问题标题】:CoreData With iCloud, Not working with sync NotificationCoreData 与 iCloud,不与同步通知一起使用
【发布时间】:2026-01-25 07:45:02
【问题描述】:

我正在使用 icloud 开发 coredata。 我有这个问题。 除了同步通知之外,带有 icloud 的 coredata 工作正常~ 我的代码在这里~

NSNotificationCenter.defaultCenter().addObserver(self, 
    selector: "changedDataOniCloud:", 
    name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, 
    object: nil)

并假设收到下面的同步通知,

func changedDataOniCloud(notification: NSNotification) {
    self.textView.text = "changedDataOniCloud"
}

我有 iPhone 和 iPad。 如果在 iphone 中更改了数据,则 ipad 获取同步数据并且更改通知必须响应。 同步数据工作正常,但通知不起作用!

请检查我在 github 中的项目 https://github.com/beauspiring/ios/blob/coredata_icloud/Example/ViewController.swift (分支:coredata_icloud)

【问题讨论】:

    标签: swift core-data notifications synchronization icloud


    【解决方案1】:

    我解决了这个问题。

    这是一个很好的参考:https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/UsingCoreDataWithiCloudPG/UsingSQLiteStoragewithiCloud/UsingSQLiteStoragewithiCloud.html#//apple_ref/doc/uid/TP40013491-CH3-SW3

    我这里改了addObserver代码~

    NSNotificationCenter.defaultCenter().addObserverForName(
        NSPersistentStoreDidImportUbiquitousContentChangesNotification, 
        object: self.moc.persistentStoreCoordinator, 
        queue: NSOperationQueue.mainQueue(), 
        usingBlock: { (noti: NSNotification) -> Void in
                self.textView.text = "Ubiquitous Content Changes"
    })
    

    object和queue很重要的两个参数 谢谢我的自己:)

    【讨论】: