我是一个快速学习者。我正在开发一个项目,我正在使用嵌套在dispatch_after
函数内的NSTimer
GCD命令。代码的其他部分执行多次迭代,其中一个是invalidate
计时器。我成功地使计时器无效。但即使在使计时器无效之后,dispatch_ after
块也会执行一次。该响应已经成为我项目中的一个错误。所以我想知道是否有任何方法或方法来阻止或终止dispatch_after
方法处于等待状态,类似于Invalidate
方法停止NSTimer
。对不起,如果我很傻。
timer2=NSTimer.scheduledTimerWithTimeInterval(Double(t.a+t.b), target: self, selector: "updateSequential:", userInfo: nil, repeats: false)
//This is the call for NSTimer.
var f = 0
func updateSequential(timer2:NSTimer)
{
var x = self.f //Setting the Initial value for sequential order
self.noDispLabel.text = String(x+1)
print("\(x)")
var content=self.imageArray[x]
self.imageDisp.image=nil
self.titleDispLabel.text=nil
self.progressBar.setProgress(5.0, animated: true)
var delay = 5.0 * Double(NSEC_PER_SEC)
var time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue())
{
if(self.timer2 != nil)
{
self.imageDisp.image=UIImage(named:content.imageName)
self.titleDispLabel.text=content.imageTitle
self.progressBar.setProgress(0.0, animated: false)
}
}
if( self.f < 4) //Increment based on the condition
{
self.f++
}
else
{
self.f = 0
}
if(self.q==0) // q is a global key variable referenced to invalidate the timer.
{
self.timer2=NSTimer.scheduledTimerWithTimeInterval(8.0, target: self, selector: "updateSequential:", userInfo: nil, repeats: false)
}
else
{
[timer2.invalidate]
self.timer2 = nil
}
}
此处dispatch_after块必须与NSTimer invalidate一起失效。
答案 0 :(得分:0)
你可以这样做......
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC);
XYZBlockResponse *response = [[XYZBlockResponse alloc] init];
dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
if (!response.cancelBlock)
NSLog(@"XYXBlock executed");
else
NSLog(@"XYXBlock did not execute");
});
response.cancelBlock = YES; // Set YES or NO.
XYZBlockResponse类很简单......
@interface XYZBlockResponse : NSObject
@property (assign) BOOL cancelBlock;
@end