-(void)btnClick:(id)sender
{
NSLog(@"btnClick");
dispatch_queue_t queue=dispatch_get_global_queue(0, 0);
dispatch_source_t timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 2*NSEC_PER_SEC, 1*NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
dispatch_async(dispatch_get_main_queue(), ^{
self.label1.text=[NSString stringWithFormat:@"%d", arc4random_uniform(1000000)];
});
});
dispatch_resume(timer);
}
当我点击按钮时,label1.text.value只显示一次,但我希望它每2秒钟更新一次。请帮帮我``
答案 0 :(得分:0)
试试这个:
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(yourMethod) userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
在yourMethod
执行此操作:
-(void)yourMethod{
Self.label1.text = [NSString stringWithFormat:@"%d", arc4random_uniform(1000000)];
}
希望这会有所帮助.. :)
答案 1 :(得分:0)
您可以创建计时器,如下所示
//Define member varialbe for timer in header file
NSTimer* timerForLocationUpdate;
//Call createTimer to create timer that will execute in each 1 min
- (void) createTimer
{
timerForLocationUpdate = [NSTimer scheduledTimerWithTimeInterval:60 /*Number of seconds*/
target:self
selector:@selector(updateLocation)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timerForLocationUpdate
forMode:NSRunLoopCommonModes];
}
//Method is called in each 1 min
- (void) updateLocation
{
}
答案 2 :(得分:0)
timer
是局部变量,-(void)btnClick:(id)sender
完成后将被释放。
因此请尝试将timer
捕获为Class变量,Instance变量或Static变量。
例如:
-(void)btnClick:(id)sender
{
NSLog(@"btnClick");
static dispatch_source_t timer;
dispatch_queue_t queue=dispatch_get_global_queue(0, 0);
timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 2*NSEC_PER_SEC, 1*NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
dispatch_async(dispatch_get_main_queue(), ^{
self.label1.text=[NSString stringWithFormat:@"%d", arc4random_uniform(1000000)];
});
});
dispatch_resume(timer);
}
它将起作用:)