zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    leetcode931
    leetcode1289
    leetcode1286
    poj Meteor Shower
    noip杂题题解
    noip2007部分题
    NOIP Mayan游戏
    某模拟题题解
    codevs 1423 骑士
    noip 邮票面值设计
  • 原文地址:https://www.cnblogs.com/yangzhifan/p/5339960.html
Copyright © 2011-2022 走看看