设为首页 加入收藏

TOP

iOS开发 - RunLoop理解(三)
2017-10-12 11:01:26 】 浏览:10046
Tags:iOS 开发 RunLoop 理解
mer:timer forMode:NSDefaultRunLoopMode];
//[[NSRunLoop currentRunLoop]addTimer:timer forMode:UITrackingRunLoopMode]; [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes]; } - (void)run { NSLog(@"-------- %@",[NSThread currentThread]); } View Code

 

    

问题:在多线程开发中,耗时操作我们一般会放在子线程中执行,请问这种线程有什么特点?

实例:假如在上面的定时器的run方法中,执行一个耗时操作,此时会卡住主线程,拖动滑动控件会很不流畅,应该如何解决?

分析:子线程中默认不会开启RunLoop循环,所以子线程在执行完任务之后就会被回收

- (void)viewDidLoad {

    [super viewDidLoad];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        //1.创建定时器

        NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];

        //2.将Timer添加到RunLoop中

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

        //3.让RunLoop运行起来

        [[NSRunLoop currentRunLoop] run];//死循环,后面的代码不会执行

        NSLog(@"+++++++++");

    });

}

- (void)run {

    //耗时操作

    [NSThread sleepForTimeInterval:1.0];

    NSLog(@"-------- %@",[NSThread currentThread]);

}
View Code

或者:

- (void)viewDidLoad {

    [super viewDidLoad];

   [NSThread detachNewThreadSelector:@selector(time2) toTarget:self withObject:nil];

}

-(void)time2{

    //创建当前线程的RunLoop

    NSRunLoop *currentLoop = [NSRunLoop currentRunLoop];

    //该方法内部自动添加到RunLoop中,并且运行模式是默认模式

    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];

    //开启RunLoop

    [currentLoop run];

}

- (void)run {

    //耗时操作

    [NSThread sleepForTimeInterval:1.0];

    NSLog(@"run ----- %@ ---- %@",[NSThread currentThread],[NSRunLoop currentRunLoop].currentMode);

}
View Code

 

 

此博文会继续不断完善及更新关于涉及到runloop的知识,如果有理解不正确或者有涉及到runloop的应用实例,请留言吧,欢迎讨论

参考文章:http://blog.ibireme.com/2015/05/18/runloop/

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇iOS ----------怎么修改xcode默认.. 下一篇iPhone与iWatch连接、控制、数据..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目