-
在开发中如何使用RunLoop?什么应用场景
-
在子线程中进行一些长期监控
-
在子线程中开启一个定时器
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) NSThread *thread;
@end
@implementation ViewController
- (IBAction)creatThread:(id)sender
{
self.thread = [[NSThread alloc]initWithTarget:self selector:@selector(task1) object:nil];
[self.thread start];
}
- (IBAction)continueThread:(id)sender
{
[self performSelector:@selector(task2) onThread:self.thread withObject:nil waitUntilDone:YES];
}
-(void)task1
{
NSLog(@"task1----%@",[NSThread currentThread]);
//1.创建RunLoop
NSRunLoop *loop = [NSRunLoop currentRunLoop];
//2.保证RunLoop不退出
[loop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
// [loop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]]; 10秒钟之后runloop退出,该方法在主线程中设置无效。
//3.开启RunLoop,默认不开启
[loop run];
NSLog(@"----end------");
}
-(void)task2
{
NSLog(@"task2----%@",[NSThread currentThread]);
}
@end