11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでNSTimerをクロージャで扱えるように拡張する

Last updated at Posted at 2015-01-15

NSTimerの拡張を作ります。

NSTimer+Closure.swift
import Foundation

// (c) 2014 Nate Cook, licensed under the MIT license

extension NSTimer {
    class func scheduledTimerWithTimeInterval(interval: NSTimeInterval, repeats: Bool, handler: NSTimer! -> Void) -> NSTimer {
        let fireDate = interval + CFAbsoluteTimeGetCurrent()
        let repeatInterval = repeats ? interval : 0
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, repeatInterval, 0, 0, handler)
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
        return timer
    }
}

使い方は以下のとおり

var count = 0
NSTimer.scheduledTimerWithTimeInterval(1, repeats: true) { timer in
    println(++count)
    if count >= 10 {
        timer.invalidate()
    }
}

こちらのものを転載させて頂きました。
https://gist.github.com/natecook1000/b0285b518576b22c4dc8

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?