YosiFZ
YosiFZ

Reputation: 7890

Cancel NSThread

This is how i create a thread:

readFromWebThread = [[NSThread alloc] initWithTarget:self selector:@selector(loadThread:) object:urlStr];

And this is how i stop it :

if ([readFromWebThread isExecuting]) {
    [readFromWebThread cancel];
}

And this is what i excute in the thread:

-(void)loadThread:(NSString*)urlStr {
    while (YES) {
        //MyStuff

        [NSThread sleepForTimeInterval:kSleepBetweenLoading];
    }
}

And the problem is that even call the cancel thread method the thread keep calling. Any idea whats can be the mistake?

Upvotes: 0

Views: 265

Answers (2)

hsoi
hsoi

Reputation: 2764

-cancel merely sets a flag. You have to check the flag.

while (!self.isCancelled) {
    // MyStuff
}

Upvotes: 2

Daij-Djan
Daij-Djan

Reputation: 50089

from the docs:

-cancel: "Changes the cancelled state of the receiver to indicate that it should exit."

==> you have to to implement the cancelation of the thread! and if it sleeps it never gets canceled

e.g.

while(YES) {
    //do a piece of work
    if([NSThread currentThread].state == canceled)
        break;
}

Upvotes: 1

Related Questions