UnsafeMutablePointer<Void> to Concrete Object Type

一世执手 提交于 2020-01-01 05:34:11

问题


How can I cast from UnsafeMutablePointer<Void> to Concrete Object Type

I've created a KVO observer and passed a custom class as context just like this

class Info : NSObject
{
}

class Foo : NSObject {
    dynamic var property = ""
}


var info = Info()

class Observing : NSObject {
    func observe1(object: NSObject) {

        object.addObserver(self, forKeyPath: "property", options: .New, context: &info)
    }

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

        println("observed \(keyPath) change:'\(change)' context: \(context)")
    }
}

let o = Observing()
var object = Foo()
o.observe1(object)
object.property = "new value"

I would like to know how to cast context back to Info class


回答1:


UnsafeMutablePointer has an initializer that takes another UnsafeMutablePointer of another type, the result being the same pointer but to the new type.

So in your case:

let infoPtr = UnsafeMutablePointer<Info>(context)
let info = infoPtr.memory

Beware though this is, as the docs describe it, "a fundamentally unsafe conversion". If the pointer you have is not a pointer to the type you convert it to, or if the memory you are now accessing it is not valid in this context, you may end up accessing invalid memory and your program will get a little crashy.



来源:https://stackoverflow.com/questions/29492817/unsafemutablepointervoid-to-concrete-object-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!