I can't seem to find much documentation on the observe(_:options:changeHandler:)
method itself. There is this page which has some example use, but there is no link to a 'real' documentation page for the method. Additionally the 'quick help' has a little bit of info, but no parameter definitions or explanation of if/how the return value or changeHandler
closure are retained.
Yes, I don't think observe(_:options:changeHandler:)
ever got its own documentation page. It's essentially a Swift-only wrapper around the Obj-C function, which can be used in its Swift translation, but is harder to use that way.
The lifetime characteristics of observe(_:options:changeHandler:)
are as straightforward as you might think. You should store the NSKeyValueObservation?
return value for as long as you need the observation, and discarding your reference (nil'ing the place where you stored it) removes the observation.
The observation — that return value — itself contains references to the change handler closure and the object, so you don't need to manage their lifetimes directly yourself.
The only gotcha here is that it's fairly easy to cause a retain cycle between a value that store the NSKeyValueObservation
and the observed object or something captured in the closure, so you may need to arrange to nil the observation manually at suitable times in your app. This is not necessarily a Bad Thing™, but just a small piece that can't be automated away. Overall, the Swift wrapper function is vastly easier to use than the Obj-C original. 😄
Please feel encouraged to use Feedback Assistant to submit a bug report against the documentation for this function.