iOS-取消延迟执行的方法cancelPreviousPerformRequestsWithTarget

前面写过一篇文章iOS-利用performSelector调用方法
iOS-利用performSelector调用方法

performSelector方法比直接调用更加灵活,多变,而且可以利用cancelPreviousPerformRequestsWithTarget方法去取消延迟执行方法。

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
发现如果是带参数,那取消时的参数也要一致,否则不能取消成功。
  [self performSelector:@selector(p_logEvent) withObject:nil];
  [self performSelector:@selector(p_logEvent) withObject:nil afterDelay:0];
  [self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:3];
  [self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:4];
  [self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:5];
    
  [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(p_logEvent) object:nil];

输出:
2017-02-09 11:42:44.770 demo[11966:4240437] demo
2017-02-09 11:42:51.139 demo[11966:4240437] demo
2017-02-09 11:42:52.196 demo[11966:4240437] demo
2017-02-09 11:42:53.164 demo[11966:4240437] demo

发现第二个方法被停止了,这是因为如果是带参数,那取消时的参数也要一致,否则不能取消成功。

 [self performSelector:@selector(p_logEvent) withObject:nil];
 [self performSelector:@selector(p_logEvent) withObject:nil afterDelay:0];
 [self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:3];
 [self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:4];
 [self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:5];
    
 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(p_logEvent) object:@"demo"];//不能取消成功。参数不匹配

输出:
2017-02-09 11:45:04.513 demo[12369:4243181] demo
2017-02-09 11:45:04.517 demo[12369:4243181] demo

object为demo的方法全都被取消了

[self performSelector:@selector(p_logEvent) withObject:nil];
[self performSelector:@selector(p_logEvent) withObject:nil afterDelay:0];
[self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:3];
[self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:4];
[self performSelector:@selector(p_logEvent) withObject:@"demo" afterDelay:5];
    
[NSObject cancelPreviousPerformRequestsWithTarget:self];//可以成功取消全部。

2017-02-09 11:48:48.899 demo[12990:4246949] demo

cancelPreviousPerformRequestsWithTarget不能够取消没有延迟参数的performSelector方法

你可能感兴趣的:(iOS-取消延迟执行的方法cancelPreviousPerformRequestsWithTarget)