UnsafeMutablePointer <Void> for a specific object type

How can I cast from UnsafeMutablePointer<Void> to a specific object type

I created a KVO observer and passed the custom class as a context, 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 return the context to the Info class

+6
source share
1 answer

UnsafeMutablePointer has an initializer that accepts another UnsafeMutablePointer different type, the result will be the same pointer, but a new type.

So in your case:

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

Beware though this is, as the docs describe, a “fundamentally unsafe conversion.” If the pointer you have is not a pointer to the type you are converting to, or if access to it that you are currently accessing is invalid in this context, you can access invalid memory and your program will be a bit emergency.

+12
source

Source: https://habr.com/ru/post/984791/


All Articles