在给定以下代码的情况下,如何访问类“self”实例以调用类实例方法。如果我尝试 self.callSomeClassIntance(),如图所示,我会从编译器收到“无法从捕获上下文的闭包形成 AC 函数指针”错误。我尝试 info.callSomeClassInstance(),但这会给出“无成员 callSomeClassInstance”错误。如果删除了一行代码 xxxx.callSomeClassIntance(),代码将正确触发时间。
import Foundation
class Foo {
func callSomeClassIntance() {}
func start() {
let runLoop : CFRunLoopRef = CFRunLoopGetCurrent();
var context = CFRunLoopTimerContext(version: 0, info: unsafeBitCast(self, UnsafeMutablePointer<Void>.self), retain: nil, release: nil, copyDescription: nil)
let timer : CFRunLoopTimerRef = CFRunLoopTimerCreate(kCFAllocatorDefault, 0.1, 3.0, 0, 0, cfRunloopTimerCallback(), &context);
CFRunLoopAddTimer(runLoop, timer, kCFRunLoopCommonModes);
CFRunLoopRun()
}
func cfRunloopTimerCallback() -> CFRunLoopTimerCallBack {
return { (cfRunloopTimer, info) -> Void in
print("Fire timer...")
// need self context here to call class instance methods
self.callSomeClassIntance()
}
}
}