Very short trick: stop NSTimer
Tuesday, June 16, 2009 The use of timers NSTimer in the development of applications for Apple iPhone is very frequent and not only in making games. One of the problems with which you can run into is the asynchronous timer itself, which can lead, during the arrest of one or more timers, the crash of our application. When you want to stop one or more timers, where repeats is set to YES it invokes the invalidate who, exactly, stop the timer. For example the code below activates a timer that invokes the method myTimerMethod every 5 seconds:
- / /
- / / MyTimer is defined as global
- / /
- scheduledTimerWithTimeInterval : 5.0 myTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0
- target: self
- ( myTimerMethod ) selector: @ selector (myTimerMethod)
- userInfo: nil
- ] ; repeats: YES];
- / /
- ) myTimerMethod { - (Void) (myTimerMethod
- / / Do ...
- )
If we were we would stop the timer:
- ; [MyTimer invalidate];
However, "invalidating" the timer make "dangerous" too variable - global - myTimer So the best method - and safe - to stop a timer could be:
- myTimer != nil ) { if (myTimer! = nil) (
- ; [MyTimer invalidate];
- ; myTimer = nil;
- )
This procedure may be useful to reset a timer (global):
- myTimer != nil ) { if (myTimer! = nil) (
- ; [MyTimer invalidate];
- ; myTimer = nil;
- / / Reset the timer to 25 seconds
- 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