Skip to content

Instantly share code, notes, and snippets.

@kiichi
Created July 7, 2015 02:28
Show Gist options
  • Select an option

  • Save kiichi/01d3ac87ee9de94dd608 to your computer and use it in GitHub Desktop.

Select an option

Save kiichi/01d3ac87ee9de94dd608 to your computer and use it in GitHub Desktop.
Swift 2.0, Protocol, Delegate and "More Accurate" Timer Example using GC
import UIKit
protocol SomethingDelegate {
func didUpdateSomething(SomethingHelper:SomethingHelper)
}
// Use CADisplayLink for more "averaged" timer interval
class SomethingHelper : NSObject{
private var timer : CADisplayLink!
private var currentIntervalInSec = 0;
var delegate: SomethingDelegate?
required init(intervalInSec:Double){
super.init()
self.timer = CADisplayLink(target: self, selector: Selector("tick"))
self.timer.frameInterval = Int(intervalInSec * 60.0)
}
deinit {
stop()
}
func tick(){
self.delegate?.didUpdateSomething(self)
}
func start(){
self.timer.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
func stop(){
self.timer.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
}
class DetailViewController: UIViewController, SomethingDelegate {
private var helper = SomethingHelper(intervalInSec: Double(2.0))
@IBOutlet weak var SomethingView: SomethingView!
override func viewDidLoad() {
super.viewDidLoad()
self.helper.delegate = self;
self.helper.start()
}
func didUpdateSomething(SomethingHelper:SomethingHelper){
print(NSDate.timeIntervalSinceReferenceDate())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment