在子线程中添加定时器并且时间到后退出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

 

posted @ 2016-03-31 21:26  张凯泽  阅读(429)  评论(0编辑  收藏  举报