在 swift 2 中使用 UnsafeMutablePointer 和 CFRunLoopObserverContext
Using UnsafeMutablePointer and CFRunLoopObserverContext in swift 2
我有以下代码
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.
自己修好了,原来回调中的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
...
我有以下代码
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.
自己修好了,原来回调中的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
...