Justin Damn Moore Justin Damn Moore - 2 years ago 230
Swift Question

Adding observer for KVO without pointers using Swift

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

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

[clearContentView addObserver:self

I have two overloaded methods to choose from to add an observer for KVO with the only difference being the context argument:

clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, context: CMutableVoidPointer)
clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, kvoContext: KVOContext)

With Swift not using pointers, I'm not sure how to dereference a pointer to use the first method.

If I create my own KVOContext constant for use with the second method, I wind up with it asking for this:

let test:KVOContext = KVOContext.fromVoidContext(context: CMutableVoidPointer)

EDIT: What is the difference between CMutableVoidPointer and KVOContext? Can someone give me an example how how to use them both and when I would use one over the other?

EDIT #2: A dev at Apple just posted this to the forums: KVOContext is going away; using a global reference as your context is the way to go right now.

Answer Source

Now that KVOContext is gone in Xcode 6 beta 3, you can do the following. Define a global (i.e. not a class property) like so:

let myContext = UnsafePointer<()>()

Add an observer:

observee.addObserver(observer, forKeyPath: …, options: nil, context: myContext)

In the observer:

override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafePointer<()>) {
    if context == myContext {
    } else {
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download