This time, I will be teaching you how to use something called an "NSTimer".
These are the very useful applications of the NSTimer:
- Repeating a block of code over and over
- Checking for updates from a web server
- Creating a timer
- Checking variables, repeatedly
- Executing a block of code after a time delay
etc.
Let's see how to create a function for the Timer (just a simple Swift function, that will print "Hello World"):
func printHelloWorld() {
print("Hello World")
}
Next, let's see how we can start the timer:
var timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "printHelloWorld", userInfo: nil, repeats: true)
The above timer will call the "printHelloWorld" function every 2 seconds.
You can also create a timer, without starting it:
var timer = NSTimer(timeInterval: 2, target: self, selector: "printHelloWorld", userInfo: nil, repeats: true)
The above timer will take all variables into account, but to start it, you must add it to Swift's "Run Loop":
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
That will start the loop.
No matter what method you choose of starting the timer, you always end it like so:
timer.invalidate()
That's it for this simple tutorial! If you have any more questions or suggestions, please email me at: tajymany@gmail.com
Hope you learned something new and enjoyed it!
No comments:
Post a Comment