NSTimer 回调事件被UI交互阻塞的解决方法

1. 在子线程添加定时器,必要的时候返回主线程操作

- (void)setupTableLight {
    
    NSThread *th = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil];
    [th start];
}

- (void)threadRun {
    NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:@"myTimerMode"];
    
    while (YES) {
        [[NSRunLoop currentRunLoop] runMode:@"myTimerMode" beforeDate:[NSDate distantFuture]];
    }
}

- (void)timerRun {

    [self performSelectorOnMainThread:@selector(tableLigthChange) withObject:nil waitUntilDone:YES];
}

- (void)tableLigthChange {

    if (self.ligthOn == YES) {
        
        self.lucklyTableHeaderLight.image = [UIImage imageNamed:@"lucklyTableHeaderTableOff"];
    } else {
    
        self.lucklyTableHeaderLight.image = [UIImage imageNamed:@"lucklyTableHeaderTableOn"];
    }
    self.ligthOn = !self.ligthOn;
}

 

2.把定时添加到当前runloop,并设置model NSRunLoopCommonModes

    NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(tableLigthChange) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer fire];

 

参考:

http://tech.dehengxu.com/blog/timer-hui-diao-shi-jian-bei-uijiao-hu-zu-sai-de-jie-jue-ban-fa/

posted @ 2016-03-31 09:39  杨智帆  阅读(366)  评论(0编辑  收藏  举报