在子线程中添加定时器并且时间到后退出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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步