6.18 Exiting Threads and Timers

本文介绍了在Objective-C中如何正确地停止线程(NSThread)及定时器(NSTimer),并提供了一个具体的示例代码,展示了如何使用线程取消机制来避免内存泄漏等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


停止线程,停止定时器

NSThread *thread = /* Get the reference to your thread here */

[thread cancel];

NSTimer *timer = /* Get the reference to your timer here */

[timer invalidate];

请注意在退出线程时不要用exit,因为用exit的话,线程没机会清理现场,会造成内存泄露。

不过,我还真不知道如何来调用exit,因为他是类方法,一调用就报错:No visible @interface for 'NSThread' declares the selector 'exit'

看个例子


- (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");

    }

}


- (void) stopThread{

    NSLog(@"Cancelling the Thread");

    [self.myThread cancel];

    NSLog(@"Releasing the thread");

    self.myThread = nil;

}


-(void)test6_18

{

    self.myThread = [[NSThread alloc] initWithTarget:self

                                            selector:@selector(threadEntryPoint)

                                              object:nil];

    [self performSelector:@selector(stopThread)

               withObject:nil

               afterDelay:6.0f];

    [self.myThread start];

}


输出:

2014-03-13 15:57:32.305 cookbook[811:360b] Thread Entry Point

2014-03-13 15:57:36.307 cookbook[811:360b] Thread Loop

2014-03-13 15:57:38.306 cookbook[811:a0b] Cancelling the Thread

2014-03-13 15:57:38.308 cookbook[811:a0b] Releasing the thread

2014-03-13 15:57:40.309 cookbook[811:360b] Thread Loop

2014-03-13 15:57:40.310 cookbook[811:360b] Thread Finished


从打印的结果可以看出,虽然线程cancel了,但是它在睡醒之后却仍然执行了一次。比较好的做法是在睡醒之后再去判断下线程是否取消了,然后在执行,如上被注释掉得那部分。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值