mohamede1945
mohamede1945

Reputation: 7198

UnsafeMutablePointer<Void> to Concrete Object Type

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

Upvotes: 6

Views: 2949

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40955

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.

Upvotes: 13

Related Questions