即使我在阅读其他链接后执行"invalide"one_answers"nil",我的计时器也不会停止。我的代码如下:
@property(nonatomic,strong) NSTimer *mytimer;
- (void)viewDidLoad {
[self performSelectorOnMainThread:@selector(updateProgressBar:) withObject:nil waitUntilDone:NO];
<do some other work>
}
- (void) updateProgressBar :(NSTimer *)timer{
static int count =0;
count++;
NSLog(@"count = %d",count);
if(count<=10)
{
self.DownloadProgressBar.progress= (float)count/10.0f;
}
else{
NSLog(@"invalidating timer");
[self.mytimer invalidate];
self.mytimer = nil;
return;
}
if(count <= 10){
NSLog(@"count = %d **",count);
self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];
}
}
1) 即使计时器无效,计时器也会中网运行。否则,在计数>10后,计时器条件被满足,并且计数继续递增。
2) 我想在非主线程上执行此操作。我想在启动计时器后继续使用viewdidload()。如何做到这一点?
我访问了SO上的其他链接,我只知道在计时器指针上调用invalide和nil。我仍然面临着问题。有人能告诉我这里缺少什么吗?我能做些什么来在后台线程上运行updateProgressBar并更新进度条?
不需要每次都安排一个计时器,只安排一次,计时器就会每秒启动一次,例如你可以像下面这样做,
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSelectorOnMainThread:@selector(startTimerUpdate) withObject:nil waitUntilDone:NO]; //to start timer on main thread
}
//hear schedule the timer
- (void)startTimerUpdate
{
self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateProgressBar:) userInfo:nil repeats:YES];
}
- (void) updateProgressBar :(NSTimer *)timer{
static int count =0;
count++;
NSLog(@"count = %d",count);
if(count<=10)
{
//self.DownloadProgressBar.progress= (float)count/10.0f;
NSLog(@"progress:%f",(float)count/10.0f);
}
else
{
NSLog(@"invalidating timer");
[self.mytimer invalidate];
self.mytimer = nil;
return;
}
if(count <= 10){
NSLog(@"count = %d **",count);
}
}
我认为您正在多次调度计时器。我想10次。只需将时间安排一次,或者如果需要多次,则使其无效。
根据评论更新:从viewdidload和addobserver中调度计时器意味着任务通知。您的任务何时完成使计时器失效。并在计时器的选择器方法中更新您的进度,这样当您使其无效时,它将自动停止进度条。
第二件事:在移动另一个视图控制器之前,您应该使计时器无效,因为这个对象在无效之前一直处于活动状态。
希望这将是地狱:)