-
-
Save apple-avadhesh/a1b8c6e0eae84600277c910247fae244 to your computer and use it in GitHub Desktop.
Swift 2.0, Protocol, Delegate and Timer Example using GC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Swift 2.0 | |
import UIKit | |
protocol SomethingDelegate { | |
func didUpdateSomething(SomethingHelper:SomethingHelper) | |
} | |
class SomethingHelper { | |
private var timer : dispatch_source_t! = nil | |
private var currentIntervalInSec = 0; | |
var delegate: SomethingDelegate? | |
required init(intervalInSec:Double){ | |
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) | |
dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, 0), UInt64(intervalInSec*Double(NSEC_PER_SEC)), 0) | |
dispatch_source_set_event_handler(self.timer, { | |
self.delegate?.didUpdateSomething(self) | |
}); | |
} | |
deinit { | |
stop() | |
} | |
func start(){ | |
dispatch_resume(self.timer) | |
} | |
func stop(){ | |
dispatch_suspend(self.timer) | |
} | |
} | |
// For example. | |
class DetailViewController: UIViewController, SomethingDelegate { | |
private var helper = SomethingHelper(intervalInSec: Double(2.0)) | |
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