2011-06-20 27 views
0

我的程序中有一个线程。它由NSTimer运行。当我停止我的NSThread或NSTimer。它会阻止我的主题。但是当我再次想要在我的程序中运行该线程时,它显示出我以前的线程不会停止。所以之前的线程和当前线程一起运行。我的程序如下。iphone - 线程不停止,为​​什么它运行在我的程序背景上。?

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

我我的程序有两粒扣一个启动线程另一个是停止线程。第一次运行和停止线程它正常工作。但第二次(停止线程后)当我再次想要运行线程时,它向我显示,前一个线程不停止,两个线程同时运行。请帮帮我。

如何停止一个线程,当我想再次运行它的线程与前一个运行一个新的线程没有。

+2

嘿现在你在这里停止定时器不是线程。并且就线程而言,无论它们的方法体是什么,都可以运行多个线程。即你可以有多个线程'startTimerThread' –

+0

,哪些是你想在实际创建新的线程或只是运行前一个。? –

回答

1

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

这将停止“当前”线程。

要了解更多有关停止线,是指其类引用here,并检查了“退出”的方法。

所以,如果在主线程调用[NSThread exit],将退出主线程。

相关问题