ios - iPhone 和 Apple Watch 应用程序之间 Core Data SQLite 存储更改的通知

标签 ios core-data watchkit apple-watch

我有一个 iPhone (iOS 8) 和 Apple Watch (watchOS 1) 应用程序,它们使用 Core Data(SQLite 商店,位于共享应用程序组中)共享数据。这两个应用程序都使用放置在共享框架中的相同数据访问代码。 NSPersistentStoreCoordinator 按以下方式设置:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let sharedContainerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(self.sharedAppGroup)!
    let storeURL = sharedContainerURL.URLByAppendingPathComponent(self.databaseName)
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    var error: NSError? = nil
    if coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
        fatalError("Unable to add persistent store: \(error)")
    }

    return coordinator
}()

根据我的理解,在运行时每个应用程序都有自己的 NSPersistenStoreCoordinator 实例(因为 iPhone 应用程序和 WatchKit 扩展确实有完全独立的地址空间),但是这两个应用程序连接到完全相同的 SQLite 数据库文件。

当 Watch 应用更改公共(public) SQLite 存储中的某些数据时,如何通知 iPhone 应用?反之亦然:当 iPhone 应用更改公共(public)持久存储中的某些数据时,如何通知 Watch 应用?

最佳答案

我发现非常满意的解决方案是使用 MMWormhole图书馆。

它通过使用 CFNotificationCenter Darwin Notifications 和在共享应用程序组中写入/读取数据文件来工作,从而导致 iOS 应用程序和应用程序扩展(Watch 应用程序、今天的小部件等)之间的即时通信。

基本代码如下:

  • 虫洞初始化

    wormhole = MMWormhole(applicationGroupIdentifier: appGroup, optionalDirectory: nil)
    
  • 将数据对象传递给虫洞

    let payload = ["Key": "Value"]
    wormhole.passMessageObject(payload, identifier: theSameMessageIdentifier)
    
  • 监听来自虫洞的传入对象

    wormhole.listenForMessageWithIdentifier(theSameMessageIdentifier) { message -> Void in
    
        if let payloadDictionary = message as? Dictionary<String, String> {
            // Do some work
        } 
    }
    

就这么简单。

关于ios - iPhone 和 Apple Watch 应用程序之间 Core Data SQLite 存储更改的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31968833/

相关文章:

swift - WatchKit InterfaceController 有条件地在 sendMessage :replyHandler: 中播放触觉

iphone - 给定字体的字符串长度以适应 UITextView

ios - 不支持推送导航 Controller

ios - 单例核心数据方法

ios - 保存子上下文时获取 NSFetchedResultsController 的批量更新

html - watchOS 上不存在 ".SFUIText-Regular"

ios - WatchKit:从 Long Look 的静态接口(interface)切换?

ios - MonoTouch.Dialog - 卡住顶行?

mysql - 将 WordPress 博客解析为应用程序

ios - 核心数据 - 如何跟踪实体集的子集