在observeValueForKeyPath中无法识别ios swift CMutableVoidPointer

sam*_*ous 9 objective-c void-pointers ios swift

我试图在我的Swift类中使用NSObject(NSKeyValueObserving),但我遇到了类型问题.Xcode抱怨它不理解以下代码中'context'参数的CMutableVoidPointer类型:

override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: CMutableVoidPointer)
Run Code Online (Sandbox Code Playgroud)

我使用CMutableVoidPointer,因为Objective-C定义将'context'参数键入为void*.

我在编译时遇到的确切错误是:"使用未声明的类型'CMutableVoidPointer'".

我正在使用Xcode Beta 3.

任何帮助,将不胜感激.

sbo*_*oth 1

以下是根据使用 Swift 与 Cocoa 和 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)
    }
}
Run Code Online (Sandbox Code Playgroud)