iOSiOS程序员

iOS 开发-运行循环RunLoop常驻线程(五)

2017-01-19  本文已影响60人  037e3257fa3b

假如,我们需要在一个子线程中执行多个任务,但是,多个任务又不是连续的。这时就需要我们在开启一条子线程后,一直保持线程处于运行或者就绪状态,而不至于执行完操作后就释放掉了。

1常驻线程

#import "ViewController.h"

@interface ViewController ()
/** 注释 */
@property (nonatomic, strong) NSThread *thread;
@end

@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //1.创建线程
    self.thread = [[NSThread alloc]initWithTarget:self selector:@selector(task1) object:nil];
    
    [self.thread start];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 在创建的子线程中执行task2方法,每次点击的时候执行。
    [self performSelector:@selector(task2) onThread:self.thread withObject:nil waitUntilDone:YES];
}

-(void)task1
{
    NSLog(@"task1---%@",[NSThread currentThread]);
    //    while (1) {
    //       NSLog(@"task1---%@",[NSThread currentThread]);
    //    }
    //解决方法:开runloop
    //1.获得子线程对应的runloop
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    
    //保证runloop不退出,必须要有一个port或timer
    //NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
    //[runloop addTimer:timer forMode:NSDefaultRunLoopMode];
    [runloop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    
    //2.默认是没有开启
    [runloop run];
    
    NSLog(@"---end----");
}

-(void)task2
{
    NSLog(@"task2---%@",[NSThread currentThread]);
}
@end

2.Runloop中自动释放池的创建和释放
1)第一次创建:启动runloop
2)最后一次销毁:runloop退出的时候
/3)其他时候的创建和销毁:当runloop即将睡眠的时候销毁之前的释放池,重新创建一个新的。

上一篇下一篇

猜你喜欢

热点阅读