Problem:
You want to stop the thread or timer from running, or prevent it from triggering again.
Scheme:
For timers, use the Nstimer instance method invalidate.
for threads, use the Cancel method。 Avoid using the exit method in threads, because when you call exit, the thread has no chance to clean up and a resource leak occurs when your application ends.
/**//**/; [Timer invalidate];
The exit of the thread is somewhat complex. When the thread is in hibernation, its cancel method is called, and the thread's loop still executes all its tasks before exiting.
For example:
- (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)Object: nil];
[Self performselector: @selector (stopthread) withobject:nil Afterdelay:3.0f]; [Self.mythread start];
returnYES;}
Print as
Thread Loopthread finished
You can clearly see that even if the cancel request has been triggered in the middle of the loop, our thread will still complete the current loop before exiting. This is a very common trap to check if a thread has been cancel before performing a task, and it is easy to avoid external influences on internal thread loops. By rewriting the above code, we check the external impact before executing the task to determine if the thread is being cancel. The following code:
- (void) threadentrypoint{@autoreleasepool {NSLog (@"Thread Entry Point"); while([[Nsthread currentthread] iscancelled] = =NO) {[Nsthread sleepfortimeinterval:4]; if ([[Nsthread currentthread] iscancelled] = = NO) { NSLog (@"Thread Loop"); } } NSLog (@"Thread finished"); }}
GCD13: Exiting Threads and timers