我有以下代码
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上。
答案 0 :(得分:2)
我自己修正了,结果是回调中的context
实际上是观察者上下文的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
...