在子线程中添加定时器并且时间到后退出runloop

Posted 张凯泽

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在子线程中添加定时器并且时间到后退出runloop相关的知识,希望对你有一定的参考价值。

//
//  ViewController.m
//  trefeeg
//
//  Created by 张凯泽 on 16/3/30.
//  Copyright © 2016年 rytong_zkz. All rights reserved.
//

#import "ViewController.h"
static int count = 10;
@interface ViewController ()
{
    BOOL end1;
    NSThread * thread;
    //NSTimer * timer;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadClick) object:nil];
    [thread start];
     //timer=[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
    
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchesEnded");
    [self performSelector:@selector(performClick) onThread:thread withObject:nil waitUntilDone:NO ];
}
-(void)performClick
{
    NSLog(@"performClick");
}
-(void)threadClick
{
    @autoreleasepool {
        NSLog(@"threadClick%@",[NSThread currentThread]);
        NSTimer * timer=[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerClick:) userInfo:nil repeats:YES];
       // NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerClick:) userInfo:nil repeats:YES];
    [timer fire];
    do {
        [[NSRunLoop currentRunLoop ]addTimer:timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        //[[NSRunLoop currentRunLoop]run];
    
        NSLog(@"____________%@",[NSThread currentThread]);
    }while (!end1);
        NSLog(@"%@",[NSThread currentThread]);

    }
        
}
-(void)timerClick:(NSTimer*)timer
{
    NSLog(@"timerClick%@",[NSThread currentThread]);
    NSLog(@"count = %d",count);
    if (count==0) {
        CFRunLoopStop(CFRunLoopGetCurrent());
        //end1 = YES;
    }
        count--;
    
    
}
@end

 

以上是关于在子线程中添加定时器并且时间到后退出runloop的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发 在异步线程里面添加定时器,或者perform afterDelay时不响应的问题

在子线程中使用runloop,正确操作NSTimer计时的注意点 三种可选方法

iOS中的定时器

ios子线程怎样能开启NSTimer

英语run和runtime区别是啥?

runloop和线程有什么关系?