[iOS][Runloop]:定时器事件和拖拽事件不冲突解决方案

Snip20181019_1.png

场景:当主线程默认的runloop模式是 NSDefaultRunLoopMode模式,而textview控件拖拽时是在UITrackingRunLoopMode模式下工作的,这样造成在拖拽时NSTimer停止工作

场景1

创建方式1
// 系统默认帮你将timer加入runloop
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
创建方式2
//2.添加到runloop中,指定运行模式为NSDefaultRunLoopMode(默认)
    //只有当runloop处于NSDefaultRunLoopMode运行模式下的时候定时器才会工作
    /*
     第一个参数:定时器对象
     第二个参数:需要指定runloop的运行模式
     */
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

以上两种方式都会出现拖拽控件卡顿的现象

解决:1、将NSTimer换成UITrackingRunLoopMode或者NSRunLoopCommonModes模式下工作,这样就能解决以上问题

[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

问题:如果有耗时操作的情况下,拖拽会出现主线程卡顿的情况

-(void)timerMethod{
    [NSThread sleepForTimeInterval:1.0];//添加模拟耗时操作阻塞主线程
    static int num = 0;
    NSLog(@"%@,%d",[NSThread currentThread],num++);
}

解决2:将定时器放在子线程中处理
自定义一个HMPTread类集成NSTread,在子线程中开启runloop

HMPTread *tread = [[HMPTread alloc]initWithBlock:^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"来了老弟");
    }];
    [tread start];
//注意 NSLog(@"来了老弟");这句是无法打印的,因为 [[NSRunLoop currentRunLoop] run];在子线程中死循环无法执行到这一步,而 [tread start];这句是在主线程中是可以执行到的

问题:创建的timer干不掉,无法控制timer
解决:通过一下方式外界也可以控制timer

#import "ViewController.h"
#import "HMPTread.h"

@interface ViewController ()
@property(nonatomic ,assign) BOOL finised;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _finised = YES;
    
    [self timer1];
  
}

-(void)timer1
{

    HMPTread *tread = [[HMPTread alloc]initWithBlock:^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

        while(_finised){
            [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceReferenceDate:0.01]];
        }
        
        NSLog(@"来了老弟");
    }];
    [tread start];
}
-(void)timerMethod{
    [NSThread sleepForTimeInterval:1.0];

    static int num = 0;
    NSLog(@"%@,%d",[NSThread currentThread],num++);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    _finised = NO;
}


@end

效果图

Snip20181019_3.png
一个有意思的尝试

干掉主线程

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [NSThread exit];\\ 外界可以通过这个类方法进行对主线程干预,界面的控件拖拽不动
}

问题:我如何在子线程中用这个方法开启子线程的循环又能实现外界对timer的控制呢

[[NSRunLoop currentRunLoop] run];

可以通过一下方式,在timerMethod方法中干掉线程是干掉的是子线程,而主线程依然工作

#import "ViewController.h"
#import "HMPTread.h"

@interface ViewController ()
@property(nonatomic ,assign) BOOL finised;
@end

@implementation ViewController

- (void)viewDidLoad
{
   [super viewDidLoad];
   _finised = NO;
   
   [self timer1];
 
}

-(void)timer1
{

   HMPTread *tread = [[HMPTread alloc]initWithBlock:^{
       NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
       [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

//        while(_finised){
//            [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceReferenceDate:0.01]];
//        }
       [[NSRunLoop currentRunLoop]run];
       
       NSLog(@"来了老弟");
   }];
   [tread start];
}
-(void)timerMethod{
   [NSThread sleepForTimeInterval:1.0];
   if (_finised) {
       [NSThread exit];
   }
   static int num = 0;
   NSLog(@"%@,%d",[NSThread currentThread],num++);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
   _finised = YES;
//    [NSThread exit];
   
}
Snip20181019_4.png
NSTimer定时器不精准

用GCD

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //创建gcd定时器
   self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    //设置定时器
    dispatch_time_t start = DISPATCH_TIME_NOW;
    dispatch_time_t interval = 1.0*NSEC_PER_SEC;
    dispatch_source_set_timer(self.timer, start, interval, 0);
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"---------%@",[NSThread currentThread]);
    });
    //启动定时器
    dispatch_resume(self.timer);
    //子线程一旦开启,gcd会自动开启runloop
    
}

GCD会自动开启子线程的runloop,不用手动添加,这是GCD自动封装的

总结

1.保证程序不退出
2.负责监听所有的事件: 触摸(UI界面的处理),时钟,网络事件
NSDefaultRunLoopMode -- 时钟,网络事件
NSRunLoopCommonModes -- 用户交互(UI事件处理)

3.RunLoop 它还需要做一件事情 UI的绘制!! 在一次RunLoop循环中要绘制屏幕上所有的点!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,200评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,526评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,321评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,601评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,446评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,345评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,753评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,405评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,712评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,743评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,529评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,369评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,770评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,026评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,301评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,732评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,927评论 2 336

推荐阅读更多精彩内容

  • 说明iOS中的RunLoop使用场景1.保持线程的存活,而不是线性的执行完任务就退出了<1>不开启RunLoop的...
    野生塔塔酱阅读 6,776评论 15 109
  • Runloop 是和线程紧密相关的一个基础组件,是很多线程有关功能的幕后功臣。尽管在平常使用中几乎不太会直接用到,...
    jackyshan阅读 9,836评论 10 75
  • 基本概念 进程 进程是指在系统中正在运行的一个应用程序,而且每个进程之间是独立的,它们都运行在其专用且受保护的内存...
    小枫123阅读 875评论 0 1
  • 什么是RunLoop Run Loop是一让线程能随时处理事件但不退出的机制。RunLoop 实际上是一个对象,这...
    ikonan阅读 605评论 1 3
  • iOS刨根问底-深入理解RunLoop 2017-05-08 10:35 by KenshinCui 概述 Run...
    mengjz阅读 1,553评论 1 10