Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform method after delay and cancel it

I want to to perform method after 2.0 seconds, but i want to be able to cancel it if before the 5 seconds if another call made , but i noticed that the cancelPreviousPerformRequestsWithTarget send object nil and performSelector send object NSString.

Can it make a problems?

-(void)startRecord:(NSString*)name {
    if (self.needToStartRecording) {
        //Cancel last call
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startRecordAfterDelay:) object:nil];
    }
    self.needToStartRecording = YES;

    [self performSelector:@selector(startRecordAfterDelay:) withObject:name afterDelay:5.0];
}

-(void)startRecordAfterDelay:(NSString*)name {
    self.needToStartRecording = NO;

    //Do My Stuff
}
like image 937
YosiFZ Avatar asked Jan 18 '26 20:01

YosiFZ


1 Answers

According to the documentation, if you pass nil, only a request performed with nil will be canceled. You should store somewhere the previous value.

The argument for requests previously registered with the performSelector:withObject:afterDelay: instance method. Argument equality is determined using isEqual:, so the value need not be the same object that was passed originally. Pass nil to match a request for nil that was originally passed as the argument.

Additionaly, if you have only this selector used with delay, you could call

[NSObject cancelPreviousPerformRequestsWithTarget:self]

This will cancel all previous request sent to self

like image 170
slecorne Avatar answered Jan 20 '26 09:01

slecorne