【问题标题】:ios swift CMutableVoidPointer not recognized in observeValueForKeyPathios swift CMutableVoidPointer 在observeValueForKeyPath 中无法识别
【发布时间】:2014-08-29 16:08:15
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

  • 在 beta 3 中,他们替换了 CMMutableVoidPointer。现在使用UnsafePointerConstUnsafePointer。查看更改说明:adcdownload.apple.com//Developer_Tools/xcode_6_beta_3_lpw27r/…
  • 谢谢。我看到。但是当我切换到 UnsafePointer 时,它给了我一个错误:对泛型类型“UnsafePointer”的引用需要 <...> 中的参数。为什么 void * 需要一个类型?
  • @samonderous:我认为是context: UnsafePointer&lt;()&gt;。只需在 Xcode 中输入 func observeValueForKeyPath 并让自动补全完成它的工作!
  • 呃,应该只是再次输入它。我最初是为 Xcode Beta 编写的。谢谢大家。
  • @JochenBedersdorfer 或者只是“关闭”,因为它“离题”,次要原因是“这个问题是由无法再复制的问题或简单的印刷错误引起的。”跨度>

标签: ios objective-c swift void-pointers


【解决方案1】:

这是根据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)
    }
}

【讨论】:

    【解决方案2】:

    这对我来说很接近,但是如果您运行的是 Swift 2,则更改字典使用字符串键,并且除了上下文之外的所有参数现在都是可选的;所以你需要确保你的函数看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2014-07-31
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多