iOS开发iOS Developer

IOSRunLoop_运行循环(NSTimer)

2017-04-04  本文已影响91人  _CLAY_

RunLoop 运行循环 (NSTimer)

目的:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,assign,getter=isfinish) BOOL finish;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _finish = YES;
    
    //子线程
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //NSTimer 之所以能被监听是因为它已经被加入到RunLoop中
        
        //初始化NSTimer---1
        //    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeup) userInfo:nil repeats:YES];
        
        //初始化NSTimer---2
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeup) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        
        while (self.finish) {
            //开启运行循环
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceReferenceDate:0.1]];
        }
        NSLog(@"当RunLoop停止的时候线程会被销毁");
        //看一下在那个线程
        NSLog(@"%@",[NSThread currentThread]);
    });
    //模式:
    /*
     1.NSDefaultRunLoopMode  -- 时钟(建议),网络事件
     2.UITrackingRunLoopMode -- 用户交互(优先处理)
     3.NSRunLoopCommonModes  -- 它并不是一个真正的模式(只是一个占位)
     可以解决滑动页面NSTimer停止的问题,但是进行耗时操作界面会卡顿.
     
     注意:子线程默认是不开启RunLoop的!!!那么子线程的代码执行完毕后就会被回收!!!
     */
    
}

- (void)timeup {
    NSLog(@"时间到%@",[NSThread currentThread]);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    _finish = NO;
}
@end
上一篇 下一篇

猜你喜欢

热点阅读