開發 WatchKit 或其他 Extension 時,Container App 與 Extension 間需共享 Core Data、UserDefaults 等持久化資料。關鍵步驟:
group.com.example.app)。DataKit),並標記 public 供雙邊引用。applicationDocumentsDirectory 指向共享容器:NSFileManager.default().containerURL(forSecurityApplicationGroupIdentifier: groupID)NSPersistentStoreCoordinator 的通知觀察(StoresWillChange 等)移至 init() 確保第一時間註冊,避免 lazy loading 導致遺漏通知。DataAccess.sharedInstance.managedObjectContext。NSNotificationCenter 僅限進程內,無法跨 App/Extension。解決方案:
使用 CoreFoundation CFNotificationCenterGetDarwinNotifyCenter(),支援跨進程廣播。Swift 需處理 C 指標轉換:
UnsafePointer 對應 const void*,UnsafeMutablePointer 對應 void*。unsafeAddressOf(self) 取得 const void*。CFNotificationCallback 為 C 函數指標,Swift 無法直接建立,需在 Objective-C 中實作 C 函數再透過 Bridging Header 暴露給 Swift 呼叫。封裝 Darwin Notification Center 並提供資料持久化傳遞。作者以 Swift 1.2 重寫為 Wormhole.swift(約 150 行),放入 Framework 共用。核心優勢:
UserInfo 字典序列化/反序列化。wormhole.listenForMessage(with:listener:)、wormhole.passMessageObject(identifier:)。DataKit-Bridging-Header.h,匯入 OC 標頭。Objective-C Bridging Header 設定路徑。@objc 或繼承 NSObject 供 Swift 呼叫。Defines Module = YES。
掌握這兩套機制,即可實現 Container App 與 Extension 的無縫資料同步與即時通知。