The use of timers ( NSTimer ) to develop applications for Apple iPhone is very frequent, not only in making games. One of the problems with which one can collide is the asynchronicity of the timer, which can lead, during the arrest of one or more timers, the crash of our application. , si invoca la invalidate che, appunto, arresta il timer. When you want to stop one or more timers, where repeats is set to YES , it invokes the invalidate who, precisely, the timer stops. For example the code below activates a timer that invokes the method myTimerMethod every 5 seconds:
1 2 3 4 5 6 7 8 9 10 11 12 | / / / / MyTimer is defined as global / / NSTimer scheduledTimerWithTimeInterval : 5.0 myTimer = [ NSTimer scheduledTimerWithTimeInterval: 5.0 Target: self ( myTimerMethod ) selector: @ selector (myTimerMethod) userInfo: nil ] ; repeats: YES]; / / void ) myTimerMethod { - (Void) {myTimerMethod / / Do ... } |
If we wanted to stop the timer:
1 | ; [MyTimer invalidate]; |
However, "invalidating" the timer make it "dangerous" the variable - global - myTimer . So the best way - and safe - to stop a timer might be:
1 2 3 4 | myTimer != nil ) { if (myTimer! = nil) { ; [MyTimer invalidate]; ; myTimer = nil; } |
This procedure can also be useful to reset a timer (global):
1 2 3 4 5 6 7 8 9 10 | myTimer != nil ) { if (myTimer! = nil) { ; [MyTimer invalidate]; ; myTimer = nil; / / Reset the timer to 25 seconds NSTimer scheduledTimerWithTimeInterval : 25.0 myTimer = [ NSTimer scheduledTimerWithTimeInterval: 25.0 Target: self ( myTimerMethod ) selector: @ selector (myTimerMethod) userInfo: nil ] ; repeats: YES]; } |










There are no comments for this post
Leave a comment