How to stop a NSThread sub-thread in iphone

本文详细解释了在Objective-C中使用NSThread创建子线程,并在主线程中尝试停止该子线程的方法。强调了`isCancelled`属性的作用及在子线程中检查并退出的必要性。

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

Q:

I created a sub-thread using NSThread in main thread

NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

5 sec later,i used [newThread cancel] in main thread to stop the sub-thread,but it didnt work,

Method MyThread: in newThread still working

so,whats the correct answer to stop newThread,THX



A:

cancal method only informs the thread that it is cancelled (as you mentioned changes theisCancelled to YES. It's then the responsibility of the thread itself to check this and exit. For example, in your MyThread: method you could do this:

// At some checkpoint
if([[NSThread currentThread] isCancelled]) {
    /* do some clean up here */
    [NSThread exit];
}

You should do this check periodically, and exit from within the thread as shown; otherwise the canceldoesn't have any effect.


@None: It means that "cancelling" a thread doesn't do what you think. When you cancel a thread, it causes isCancelled to return YES. The thread should then stop executing. It doesn't force the thread to immediately stop execution, though — that would be troublesome if it had any resources open


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值