繁体   English   中英

在observeValueForKeyPath中无法识别ios swift CMutableVoidPointer

[英]ios swift CMutableVoidPointer not recognized in observeValueForKeyPath

我试图在我的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。

任何帮助,将不胜感激。

以下是根据使用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)
    }
}

这对我来说很接近,但是如果你正在运行Swift 2,那么更改字典会使用字符串键,除了上下文之外的所有参数现在都是可选的; 所以你需要确保你的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