Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsafeMutablePointer<Void> to Concrete Object Type

Tags:

casting

swift

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

like image 620
mohamede1945 Avatar asked Apr 07 '15 13:04

mohamede1945


1 Answers

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.

like image 56
Airspeed Velocity Avatar answered Sep 23 '22 12:09

Airspeed Velocity