我有以下一点代码
private func addRunLoopObserverForSaving() {
var _self = self
withUnsafeMutablePointer(&_self) { (pSelf) -> Void in
var observerContext = CFRunLoopObserverContext(
version: 0,
info: pSelf,
retain: nil,
release: nil,
copyDescription: nil)
withUnsafeMutablePointer(&observerContext, { (pObserverContext) -> Void in
let observer = CFRunLoopObserverCreate(
kCFAllocatorDefault,
CFRunLoopActivity.BeforeTimers.rawValue,
true,
0,
{ (observer, activity, context) -> Void in
guard context != nil else { return }
let pObserverContext = UnsafeMutablePointer<CFRunLoopObserverContext>(context)
let pGraphsModel = UnsafeMutablePointer<GraphsModel>(pObserverContext.memory.info)
let z = pGraphsModel.memory
...
},
pObserverContext
)
CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode)
})
}
}
出于某些原因,行z = pGraphsModel.memory总是给我一个EXC_BAD_ACCESS.我不确定在检索存储的值时是否正确使用UnsafeMutablePointer.任何想法都表示赞赏!
PS.这发生在XCode 7 beta5上.
最佳答案 我自己修正了它,事实证明回调中的上下文实际上是观察者上下文的info成员.所以代替:
let pObserverContext = UnsafeMutablePointer<CFRunLoopObserverContext>(context)
let pGraphsModel = UnsafeMutablePointer<GraphsModel>(pObserverContext.memory.info)
let z = pGraphsModel.memory
...
应该只是
let pGraphsModel = UnsafeMutablePointer<GraphsModel>(context)
let z = pGraphsModel.memory
...