iOS多线程(二)

常见问题解惑

1.问题一

1.1以下代码打印结果

- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"task 1");
        [self performSelector:@selector(task2) withObject:nil afterDelay:.0];
        NSLog(@"task 3");
    });
    /*
     执行结果:
        线程[51489:6875868] task 1
        线程[51489:6875868] task 3
     原因:
        - (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
        1.上述方法在子线程中 运行本质本质是往Runloop中添加NSTimer
        2.子线程默认没有启动Runloop
     */
}

- (void)task2 {
    NSLog(@"task 2");
}

1.2.如何修复

1.

- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
此方法本质是:往Runloop里面添加NStimer
启动Runloop

2. 顺便记一下

- (id)performSelector:(SEL)aSelector withObject:(id)object;
此方法本质是:objc_msgsend(self,@SEL);
    dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"task 1");
        [self performSelector:@selector(task2) withObject:nil afterDelay:.0];
        NSLog(@"task 3");
        //[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc]init] forMode:NSDefaultRunLoopMode]; 这行代码可删除上行代码已经往Runloop中添加了定时器
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    });
    
    /*
     执行结果:
        线程[51489:6875868] task 1
        线程[51489:6875868] task 3
        线程[51489:6875868] task 2
     */

问题二

2.1一下代码运行结果


- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"task1");
    }];
    [thread start];
    [self performSelector:@selector(task2) onThread:thread withObject:nil waitUntilDone:YES];
}
- (void)task2 {
    NSLog(@"task2");
}
/*
 1.崩溃信息如下:
*** Terminating app due to uncaught exception 'NSDestinationInvalidException', reason: '*** -[ViewController performSelector:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform'
2. 原因:
    thread调用start 就会再子线程中执行block中的代码  执行完毕后线程就退出
    没有办法在当前thread线程中执行task2方法
*/

2.2如何修复

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"task1");
        [[NSRunLoop currentRunLoop]addPort:[[NSPort alloc]init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }];
    [thread start];
    [self performSelector:@selector(task2) onThread:thread withObject:nil waitUntilDone:YES];
}
- (void)task2 {
    NSLog(@"task2");
}
/*
 打印结果
     线程[58654:7033043] task1
     线程[58654:7033043] task2 
*/

@end

你可能感兴趣的:(iOS多线程(二))