在swift 2

时间:2015-08-08 15:17:48

标签: swift xcode7 cfrunloop

我有以下代码

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上。

1 个答案:

答案 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
...