Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios swift CMutableVoidPointer not recognized in observeValueForKeyPath

I'm trying to make use of the NSObject(NSKeyValueObserving) in my Swift class but I'm running into a type problem. Xcode is complaining that it doesn't understand the CMutableVoidPointer type for the 'context' argument in the following code:

override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: CMutableVoidPointer)

I use CMutableVoidPointer because the Objective-C definition types the 'context' argument as a void *.

The exact error I'm getting at compile-time is: "Use of undeclared type 'CMutableVoidPointer'".

I'm using Xcode Beta 3.

Any help would be appreciated.

like image 668
samonderous Avatar asked Jul 08 '14 19:07

samonderous


2 Answers

Here is the current best practice according to Using Swift with Cocoa and Objective-C:

// Add the dynamic modifier to any property you want to observe
class MyObjectToObserve: NSObject {
    dynamic var myDate = NSDate()
    func updateDate() {
        myDate = NSDate()
    }
}

// Create a global context variable
private var myContext = 0

// Add an observer for the key-path, override the observeValueForKeyPath:ofObject:change:context: method, and remove the observer in deinit.
class MyObserver: NSObject {
    var objectToObserve = MyObjectToObserve()
    override init() {
        super.init()
        objectToObserve.addObserver(self, forKeyPath: "myDate", options: .New, context: &myContext)
    }
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) {
        if context == &myContext {
            println("Date changed: \(change[NSKeyValueChangeNewKey])")
        } else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }
    deinit {
        objectToObserve.removeObserver(self, forKeyPath: "myDate", context: &myContext)
    }
}
like image 73
sbooth Avatar answered Sep 21 '22 13:09

sbooth


this was close for me, but if you're running Swift 2, the change dictionary uses String keys and all the params except the context are optional now; so you'll need to make sure your func looks like this:

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    ...
    }
like image 26
johnnyclem Avatar answered Sep 18 '22 13:09

johnnyclem