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:

Objective-C:
  1. / /
  2. / / MyTimer is defined as global
  3. / /
  4. scheduledTimerWithTimeInterval : 5.0 myTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0
  5. target: self
  6. ( myTimerMethod ) selector: @ selector (myTimerMethod)
  7. userInfo: nil
  8. ] ; repeats: YES];
  9. / /
  10. ) myTimerMethod { - (Void) (myTimerMethod
  11. / / Do ...
  12. )

If we were we would stop the timer:

Objective-C:
  1. ; [MyTimer invalidate];

However, "invalidating" the timer make "dangerous" too variable - global - myTimer So the best method - and safe - to stop a timer could be:

Objective-C:
  1. myTimer != nil ) { if (myTimer! = nil) (
  2. ; [MyTimer invalidate];
  3. ; myTimer = nil;
  4. )

This procedure may be useful to reset a timer (global):

Objective-C:
  1. myTimer != nil ) { if (myTimer! = nil) (
  2. ; [MyTimer invalidate];
  3. ; myTimer = nil;
  4. / / Reset the timer to 25 seconds
  5. scheduledTimerWithTimeInterval : 25.0 myTimer = [NSTimer scheduledTimerWithTimeInterval: 25.0
  6. target: self
  7. ( myTimerMethod ) selector: @ selector (myTimerMethod)
  8. userInfo: nil
  9. ] ; repeats: YES];
  10. )

Related Post

Was this article helpful?: Per nientePocoAbbastanzaMoltoMoltissimo
Loading ... Loading ...

There are no comments for this post

Leave a comment

TAG XHTML PERMISSIONS: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre>         // blocco generico [code][/code]       // blocco generico [as][/as]           // Actionscript [css][/css]         // CSS Style Sheet [html][/html]       // HTML [js][/js]           // Javascript [objc][/objc]       // Objective-C [php][/php]         // PHP [sql][/sql]         // SQL