O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.17. Exiting Threads and Timers

Problem

You would like to stop a thread or a timer, or prevent one from firing again.

Solution

For timers, use the invalidate instance method of NSTimer. For threads, use the cancel method. Avoid using the exit method of threads, as it does not give the thread a chance to clean up after itself, and your application will end up leaking resources:

NSThread *thread = /* Get the reference to your thread here */;
[thread cancel];

NSTimer *timer = /* Get the reference to your timer here */;
[timer invalidate];

Discussion

Exiting a timer is quite straightforward; you can simply call the timer’s invalidate instance method. After you call that method, the timer will not fire any more events to its target object.

However, threads are a bit more complicated to exit. When a thread is sleeping and its cancel method is called, the thread’s loop will still perform its task fully before exiting. Let me demonstrate this for you:

- (void) threadEntryPoint{
    
    @autoreleasepool {
        NSLog(@"Thread Entry Point");
        while ([[NSThread currentThread] isCancelled] == NO){
            [NSThread sleepForTimeInterval:4];
            NSLog(@"Thread Loop");
        }
        NSLog(@"Thread Finished");
    }
    
}

- (void) stopThread{
    
    NSLog(@"Cancelling the Thread");
    [self.myThread cancel];
    NSLog(@"Releasing the thread");
    self.myThread = nil;
    
}

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    self.myThread = [[NSThread alloc]
                     initWithTarget:self
                     selector:@selector(threadEntryPoint ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required