Adding observer for KVO without pointers using Swift

后端 未结 5 903
灰色年华
灰色年华 2020-12-05 00:28

In Objective-C, I would normally use something like this:

static NSString *kViewTransformChanged = @\"view transform changed\";
// or
static const void *kVie         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 01:26

    There is now a technique officially recommended in the documentation, which is to create a private mutable variable and use its address as the context.

    (Updated for Swift 3 on 2017-01-09)

    // Set up non-zero-sized storage. We don't intend to mutate this variable,
    // but it needs to be `var` so we can pass its address in as UnsafeMutablePointer.
    private static var myContext = 0
    // NOTE: `static` is not necessary if you want it to be a global variable
    
    observee.addObserver(self, forKeyPath: …, options: [], context: &MyClass.myContext)
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if context == &myContext {
            …
        }
        else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    

提交回复
热议问题