ios计时器只运行一次

时间:2014-08-25 02:00:22

标签: ios timer

-(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秒钟更新一次。请帮帮我``

3 个答案:

答案 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);
}

它将起作用:)