运行循环

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    // 异步函数 + 全局并发队列

    

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        //

        

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

        

        // 创建一个定时器.定时器就是一个事件源.

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

        

        // 需要将事件源添加到一个运行循环中

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

        

       // [[NSRunLoop currentRunLoop] run];// 开启一个死循环

        

        //没有这句话就不能暂停  不能暂停执行耗时操作

        CFRunLoopRun();

        

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

        

    });

}

                      

                      

- (void)test

{

    //定义了一个变量

    static int number = 0;

    

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

    //这个变量是递增的

    number ++;

    //判断如果这个变量增加到5的时候  下面的方法会停止运行循环

    if (number == 5) {

        

        // CFRunLoopGetCurrent() 活的当前的运行循环

        // CFRunLoopStop 停止当前的运行循环.

        CFRunLoopStop(CFRunLoopGetCurrent()); // 这句代码执行之后,就关闭运行循环了.就把运行循环这个死循环移除了,可以执行后续的代码.

    }

    

}

@end

posted @ 2015-09-03 12:30  记忆里的那座沙城  阅读(96)  评论(0编辑  收藏  举报