码迷,mamicode.com
首页 > 其他好文 > 详细

延时执行

时间:2015-09-03 00:41:58      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    // 运行循环本质上就是一个死循环.

    

    // 每一条线程,都有一个运行循环.默认情况下,只有主线程的运行循环是开启的.

    

    // 运行循环可以监测事件源(按钮点击/滚动/NSTimer/target)的发生,一旦有事件源发生,就会唤醒运行循环来处理这些事件.运行循环处理完时间之后,再次进入到睡眠状态,直到有新的事件将它唤醒.

    //    perform    Selector  选择   test是方法  after ...以后  Delay 延迟时间

    

    // [self performSelector:@selector(test) withObject:nil afterDelay:3].是一个特殊的事件源.需要有运行循环来监测这个事件.一旦这个事件被执行完毕,运行循环就会被自动关闭.

    

    // 子线程运行循环的开启,必须先加入事件源.

    

    

}

 

//点击方法

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

{

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

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        

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

        

        // 延时三秒执行 test 需要延时执行的代码  一块延时的代码 test表示事件源

        [self performSelector:@selector(test) withObject:nil afterDelay:3];

        

        // 开启子线程的运行循环

        // NSRunLoop :运行循环

        // run: 开启运行循环

        //子线程运行循环的开启,需要在之前加入事件源

        [[NSRunLoop currentRunLoop] run]; // 这一行代码就是一个死循环

        

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

        

    });

    

}

 

 

-(void)test

{

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

}

 

 

// 延时执行的方式3.如果当前线程是主线程,能够实现延时执行.

// 如果当前线程是子线程,默认情况下,不能执行.

- (void)afterDelay3

{

    // 延时三秒执行 test 代码

    [self performSelector:@selector(test) withObject:nil afterDelay:3];

}

 

 

// 延时执行的方式2,一般不用.

- (void)afterDelay2

{

    // 阻塞线程3秒钟 // 这种延时方式,会阻塞当前线程,效率比较低.一般不用.(调试程序的时候,可以使用.)

    [NSThread sleepForTimeInterval:3];

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

}

 

// 延时执行的方式1.

- (void)afterDelay

{

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        //

        

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

        

        // 延时执行,不会阻塞当前线程.(制定了一个延时执行的任务,相当于定了一个闹铃)

        // 这一个延时执行,是最靠谱的延时执行的方式.

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

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

        });

        

        

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

        

        

    });

}

 

 

 

@end

延时执行

标签:

原文地址:http://www.cnblogs.com/R-X-L/p/4779743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!