swift 带有Swift闭包的预定NSTimer

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 带有Swift闭包的预定NSTimer相关的知识,希望对你有一定的参考价值。

extension NSTimer {
    /**
    Creates and schedules a one-time `NSTimer` instance.
    
    - Parameters:
        - delay: The delay before execution.
        - handler: A closure to execute after `delay`.
    
    - Returns: The newly-created `NSTimer` instance.
    */
    class func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
        let fireDate = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }
    
    /**
    Creates and schedules a repeating `NSTimer` instance.
    
    - Parameters:
        - repeatInterval: The interval (in seconds) between each execution of
          `handler`. Note that individual calls may be delayed; subsequent calls
          to `handler` will be based on the time the timer was created.
        - handler: A closure to execute at each `repeatInterval`.
    
    - Returns: The newly-created `NSTimer` instance.
    */
    class func schedule(repeatInterval interval: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
        let fireDate = interval + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }
}

// Usage:
var count = 0
NSTimer.schedule(repeatInterval: 1) { timer in
    print(++count)
    if count >= 10 {
        timer.invalidate()
    }
}

NSTimer.schedule(delay: 5) { timer in
    print("5 seconds")
}

以上是关于swift 带有Swift闭包的预定NSTimer的主要内容,如果未能解决你的问题,请参考以下文章

Swift:带有@escaping 闭包的选择器返回 EXC_BAD_ACCESS

NSTimer 中的错误(Swift:Xcode)

Swift Playground 中的 NSTimer.scheduledTimerWithTimeInterval

在 Swift 中使用 NSTimer

NSTimer 中的 UserInfo 没有传递正确的信息 - Swift

Swift 完成处理程序 - 转义尾随闭包