问题描述
如何从 UnsafeMutablePointer< Void>
转换为具体对象类型
How can I cast from UnsafeMutablePointer<Void>
to Concrete Object Type
我创建了一个KVO
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"
我想知道如何将上下文投射回Info类
I would like to know how to cast context back to Info class
推荐答案
UnsafeMutablePointer
有一个初始化器,它接受另一个类型的另一个 UnsafeMutablePointer
,结果是相同的指针,
UnsafeMutablePointer
has an initializer that takes another UnsafeMutablePointer
of another type, the result being the same pointer but to the new type.
所以在你的情况下:
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.
这篇关于UnsafeMutablePointer< Void>到具体对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!