KVO - How to check if an object is an observer?

后端 未结 3 2090
傲寒
傲寒 2020-12-07 16:56

When observing a value on an object using addObserver:forKeyPath:options:context:, eventually you\'ll want to call removeObserver:forKeyPath: on th

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 17:36

    I underestand this an objective-c question. But since lots of people use Swift/objective-c together, I thought I point out the advantage of the Swift4 new API over older versions of KVO:

    If you do addObserver multiple times for KVO, then for each change you’ll get the observeValue as many as the current number of times you’ve added yourself as the observer.

    • And to remove yourself you have to call removeObserver as many times as you added.
    • Removing it more than you’ve added will result in a crash

    The Swift4 observe is far smarter and swiftier!

    • If you do it multiple times, it doesn’t care. It won’t give multiple callbacks for each change.
    • And only one invalidate of the token is enough.
    • invalidating it before beginning to observer or more times that that you’ve done observe will not result in a crash

    So to specifically answer your question, if you use the new Swift4 KVO, you don't need to care about it. Just call invalidate and you're good. But if you're using the older API then refer to Nikolai's answer

提交回复
热议问题