Fabian Steinhauer
Fabian Steinhauer

Reputation: 119

How to cancel multiple delayed performSelector calls

I have to stop the call in the fenumeration.

NSTimeInterval delay = 2;
for (NSString* sentence in sentences) {
   [sentenceHandler performSelector:@selector(parseSentence:)
                         withObject:sentence
                         afterDelay:delay];
   delay += 2;
}

How to stop this call from above? I tried:

[NSObject cancelPreviousPerformRequestsWithTarget:sentenceHandler 
    selector:@selector(parseSentence) object:nil];

but there's no effect? Does it only quit one of the many calls in the loop?

Upvotes: 9

Views: 4935

Answers (4)

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

You have two options. You could use this which would remove all queued calls to parseSentence::

[NSObject cancelPreviousPerformRequestsWithTarget:sentenceHandler];

Or you can remove each one individually (Note the colon ":" after the method parseSentence):

[NSObject cancelPreviousPerformRequestsWithTarget:sentenceHandler
                                         selector:@selector(parseSentence:)
                                           object:sentence];

Upvotes: 13

JustinP
JustinP

Reputation: 21

I had this issue, ensuring the string was identical in the performSelector and the cancelPreviousPerformRequestsWithTarget solved it for me.

Upvotes: 1

Matt
Matt

Reputation: 693

I ran into a similar issue where I was unaware that I was scheduling multiple performSelector calls on different objects so the "self" was different in each case.

I'd recommend throwing in a NSLog(@"Self: %@",self); before each of your bits of code such as:

for (NSString* sentence in sentences) {
    NSLog(@"Self: %@",self);
   [sentenceHandler performSelector:@selector(parseSentence:)
                         withObject:sentence
                         afterDelay:delay];
   delay += 2;
}

Then cancel with:

NSLog(@"Self: %@",self);
[NSObject cancelPreviousPerformRequestsWithTarget:sentenceHandler 
    selector:@selector(parseSentence) object:nil];

This will allow you to ensure you are queuing-up and releasing the selector on the right SELF.

Upvotes: 0

Ole Begemann
Ole Begemann

Reputation: 135558

Try @selector(parseSentence:) instead of @selector(parseSentence). The two are not equivalent. Also, you have to specify the object:. The documentation clearly says you can't pass nil if you haven't passed nil in the original performSelector:... call.

Upvotes: 1

Related Questions