I want to stop an NSTimer in UIRequiredPassowrdViewController
from another view SettingsTabelViewController
, so I first create the countdown:
class UIRequiredPassowrdViewController: UIViewController, UITextFieldDelegate {
var timer: NSTimer?
var remainingSeconds = 1000
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer:", userInfo: nil, repeats: true)
}
func updateTimer(timer: NSTimer) {
remainingSeconds -= 1
println(remainingSeconds)
}
func StopTimerNotication(){
println("Function Start!")
timer?.invalidate()
timer = nil
}
}
Then I call function StopTimerNotication()
from another view SettingsTabelViewController
:
@IBAction func myButtonClicked(sender: AnyObject) {
println("Button Clicked")
var myClass: UIRequiredPassowrdViewController=UIRequiredPassowrdViewController()
myClass.StopTimerNotication()
}
And I run the app, the log shows correctly countdown, button clicked and run the function, but the timer just don't get stop:
999
998
997
996
995
994
993
992
991
990
989
Button Clicked
Function Start!
988
987
986
985
How can I solve this problem?
myClass
is a newly initialised view controller, it is totally different with the view controller in which you started the timer. So to solve your problem, basically you need to find a way to tell that specific view controller to stop its timer.There are two common solutions for such case:
(1) Use notification: In your
UIRequiredPassowrdViewController
register to a specific notification, let's call itStopTimerNotification
, when you receive such notification stop the timer. And inSettingsTabelViewController
, send outStopTimerNotification
inmyButtonClicked
.(2) Use delegate: you need a simple protocol here, let's call it
StopTimerProtocol
which will probably have only on methodfunc stopTimer()
. And yourUIRequiredPassowrdViewController
needs to conform to this protocol and implement that method. Then add adelegate
property which is a type ofid<StopTimerProtocol>
toSettingsTabelViewController
. After that, when you present or pushSettingsTabelViewController
on top ofUIRequiredPassowrdViewController
set thedelegate
property. At last, inSettingsTabelViewController
whenmyButtonClicked
just callself.delegate.stopTimer()