Search code examples
iosnsthread

iOS, how to restart NSThread?


To restart the NSSthread, I'm using the code below:

- (IBAction)listen:(id)sender {
thread = [[NSThread alloc] initWithTarget:self selector:@selector(listen1) object:nil];
[thread start];
[thread cancel];
[thread start];
}

But when I built and pressed this button, I've received error: "attempt to start the thread again" Can you help me?


Solution

  • Method -cancel doesn't stop the thread, it just sets cancel flag.

    Changes the cancelled state of the receiver to indicate that it should exit.

    - (void)cancel

    The semantics of this method are the same as those used for the NSOperation object. This method sets state information in the receiver that is then reflected by the isCancelled method. Threads that support cancellation should periodically call the isCancelled method to determine if the thread has in fact been cancelled, and exit if it has been.

    You can stop a Thread only from within itself by calling [NSThread exit].


    By the way, what are you trying to achieve? Starting separate thread is almost never good idea and starting the same thread twice is twice wrong.