//第一步:创建一个新的子线程,为了不阻塞当前线程 - (NSThread *)archiveringThread { static NSThread *_thread = nil; static dispatch_once_t onceToken; __weak __typeof(self)weakSelf = self; dispatch_once(&onceToken, ^{ __strong __typeof(weakSelf)strongSelf = weakSelf; //1. 创建新的NSThread对象 _thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadStartRunMethod:) object:nil]; //2. 注意,一定要start线程对象,否则不执行 [_thread start]; }; return _thread; }
// 第二步:在新线程对象的执行函数里面,开启新线程对象的runloop - (void) threadStartRunMethod:(id)__unused object { //注意:这个方法执行是在新的子线程上,并不是当前线程对象 // 设置线程的名字 NSThread *thread = [NSThread currentThread]; [thread setName:@"所在新的子线程对象"]; // 获取当前所在线程对象的runloop NSRunloop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; // 开启runloop,开始接收事件源 [runLoop run]; }
// 第三步:在创建的新线程上,执行startArchiverData方法 - (void)scheduleArchive { [self performSelector:@selector(startArchiverData) onThread:[self archiveringThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; }
// 第四步:在所在的runloop添加NSTimer时间, 一直让runloop处于接收事件源的状态 - (void)startArchiverData { //1. 获取当前线程的runloop NSRunLoop *loop = [NSRunLoop currentRunLoop]; //.2 创建NSTimer,指定回调函数doArchiverData _archiveringTimer = [NSTimer timerWithTimeInterval:10.f target:self selector:@selector(doArchiverData) userInfo:nil repeats:YES]; //3. 将NSTimer添加到runloop [loop addTimer:_archiveringTimer forMode:NSDefaultRunLoopMode]; //4. 一直让loop执行timer事件源 while (YES) { [loop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:2.f]]; } }
// 第五步:有runloop调度执行NSTimer的回调函数 - (void)doArchiverData { NSLog(@"... doArchiverData ... \n"); }
时间: 2024-11-04 23:36:33