GCD13 :退出线程和计时器
问题:
方案:
NSThread *thread = /* Get the reference to your thread here */; [thread cancel]; NSTimer *timer = /* Get the reference to your timer here */; [timer invalidate];
例如:
- (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];
return YES; }
打印为
...
Thread Entry Point
Cancelling the Thread
Releasing the thread
Thread Loop
Thread Finished
- (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"); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。