简体   繁体   English

在observeValueForKeyPath中无法识别ios swift CMutableVoidPointer

[英]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. 我试图在我的Swift类中使用NSObject(NSKeyValueObserving),但我遇到了类型问题。 Xcode is complaining that it doesn't understand the CMutableVoidPointer type for the 'context' argument in the following code: Xcode抱怨它不理解以下代码中'context'参数的CMutableVoidPointer类型:

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 *. 我使用CMutableVoidPointer,因为Objective-C定义将'context'参数键入为void *。

The exact error I'm getting at compile-time is: "Use of undeclared type 'CMutableVoidPointer'". 我在编译时遇到的确切错误是:“使用未声明的类型'CMutableVoidPointer'”。

I'm using Xcode Beta 3. 我正在使用Xcode Beta 3。

Any help would be appreciated. 任何帮助,将不胜感激。

Here is the current best practice according to Using Swift with Cocoa and Objective-C : 以下是根据使用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)
    }
}

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; 这对我来说很接近,但是如果你正在运行Swift 2,那么更改字典会使用字符串键,除了上下文之外的所有参数现在都是可选的; so you'll need to make sure your func looks like this: 所以你需要确保你的func看起来像这样:

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    ...
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM