Ios 退出一个NSThread,当它';她在睡觉吗?
我正在创建一个运行我的方法之一的新线程: 我现在做的是:Ios 退出一个NSThread,当它';她在睡觉吗?,ios,nsthread,Ios,Nsthread,我正在创建一个运行我的方法之一的新线程: 我现在做的是: NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadFunc) object:nil]; [thread start]; 在myThreadFunc中 { while(isRunning){ [self updateSomething]; [NSThread sleepForT
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadFunc) object:nil];
[thread start];
在myThreadFunc中
{
while(isRunning){
[self updateSomething];
[NSThread sleepForTimeInterval:3.0];
}
NSLog(@"out");
}
在另一个func中,我设置了isRunning=NO
和thread=nil
或[thread cancel]
,但myThreadFunc
处于休眠状态,因此线程无法退出。
我怎样才能控制这个案子?
非常感谢。不要使用线程。使用计时器。如果某物很昂贵,将其分派到主队列以外的某个队列,并设置一些状态变量以显示它仍在运行(如果某物不打算同时运行)。然后,取消你的计时器。计时器回调函数的一个简单示例可能是:
- (void)doSomething:(NSTimer*)timer
{
// this assumes that this "something" only ever
// runs once at a time no matter what, adjust this
// to an ivar if it's per-class instance or something
static BOOL alreadyDoingSomething = NO;
if( alreadyDoingSomething ) return;
alreadyDoingSomething = YES;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self updateSomething];
alreadyDoingSomething = NO;
});
}
现在,如果您只是取消计时器,它将停止运行。当您准备再次启动它时,使用此方法安排一个新的计时器作为指定的选择器。要使其行为类似于上面的示例,可以将计时器间隔设置为3秒