我正在尝试在我的Swift类中使用NSObject(NSKeyValueObserving),但是我遇到了类型问题。 Xcode提示说它不理解以下代码中'context'参数的CMutableVoidPointer类型:
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: CMutableVoidPointer)
我使用CMutableVoidPointer,因为Objective-C定义将'context'参数键入为void *。
我在编译时遇到的确切错误是:“使用未声明的类型'CMutableVoidPointer'”。
我正在使用Xcode Beta 3。
任何帮助,将不胜感激。
最佳答案
这是根据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)
}
}
关于iOS Swift CMutableVoidPointer在observeValueForKeyPath中无法识别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24640017/