0

I'm building a Mac OS app that uses a share extension. That means its basically two apps, the main app, and the share extension app.

To communicate data between each other, I use a shared container suite like so:

 let sharedDefaults = UserDefaults.init(suiteName: "com.myapp.sharedsuite")
 let existingData = sharedDefaults?.value(forKey: "data")

 sharedDefaults?.setValue("blah", forKey: "data")

So data sharing is solved. However, I would like my main application to "listen" to when this data changes. I can't use a delegate pattern as the two apps are separate and have no reference to each other. Notifications I believe are also localized and sandboxed, so I can't use those.

That leaves KVO pattern where I would like to be notified whenever the value changes on sharedDefaults?.value(forKey: "data"). The problem is I'm not sure how to observe this value, as its not a property of my main app's View Controller class. Also, the data object could be an array of structs, not an NSObject, which I believe is a requirement to observe properties.

Any help appreciated. Thanks

user339946
  • 5,961
  • 9
  • 52
  • 97
  • Don't use `value(forKey:)` and `setValue(_:forKey:)`, use `object(forKey:)` or `data(forKey:)` instead. – Willeke Feb 15 '21 at 09:17
  • Do you want to observe the `UserDefaults` object for the `data` key or do you want to observe the view controller for changes in the array of structs? – Willeke Feb 15 '21 at 09:30
  • @Willeke I would like the view controller to be notified whenever the object for data key is changed. So I think that means observing the "data" key? – user339946 Feb 15 '21 at 18:42

0 Answers0