繁体   English   中英

iPhone-线程没有停止,为什么它在我的程序后台运行。

[英]iphone - Thread is not stopped, why it run on my program background.?

我的程序中有一个线程。 它由NSTimer运行。 当我停止我的NSThread或NSTimer时。 它停止了我的线程。 但是当我再次想在程序中运行线程时,它告诉我,上一个线程没有停止。 因此,先前的线程和当前的线程一起运行。 我的程序如下。

- (void) startTimer{
    timerThread = [[NSThread alloc] 
                             initWithTarget:self 
                             selector:@selector(startTimerThread) object:nil];

    [timerThread start];
}

-(void) startTimerThread{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
    timer = [[NSTimer scheduledTimerWithTimeInterval: 2.0
                                      target: self
                                    selector: @selector(timerTick:)
                                    userInfo: nil
                                     repeats: YES] retain];

    [runLoop run];
    [pool release];
}

- (void)stopTimer{

    [timer invalidate];
    [timer release];
    timer = nil;
}

- (void)timerTick:(NSTimer *)timer
{
    NSLog(@"THik");
}

我的程序中有两个按钮,一个用于启动线程,另一个用于停止线程。 首次运行和停止线程时,它可以正常工作。 但是第二次(停止线程之后)当我再次想要运行线程时,它告诉我,上一个线程没有停止,并且两个线程同时运行。 请帮我。

我该如何停止线程,当我想再次运行该线程时,它将运行一个新线程,而不是前一个线程。

您仅在stopTimer方法中停止计时器。 线程仍在执行。 要停止线程,可以执行[NSThread exit];

这将停止“当前”线程。

要了解有关停止线程的更多信息,请在此处参考其类参考并检查“退出”方法。

因此,如果在主线程上调用[NSThread exit] ,它将退出主线程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM