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.
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)
}
}
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>) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With