常驻线程

模仿曾经的AFN常驻线程写法,现在的YY的写法也是如此
+ (NSThread *)zyThread {
    static NSThread * _zyThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once( &oncePredicate, ^{
        _zyThread = [[NSThread alloc]initWithTarget:self
                                           selector:@selector(zyThreadEntryPoint:)
                                             object:nil];
        [_zyThread start];
    });
    return _zyThread;
}

+ (void)zyThreadEntryPoint:(id) __unused objec {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"ZY_Thread"];
        [[NSRunLoop currentRunLoop] addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];
        [[NSRunLoop currentRunLoop] run];
    }
}
使用performSelector: onThread:简单调用如下
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    [self performSelector:@selector(sayHello:)
                 onThread:[ZYThread zyThread]
               withObject:@"hello~"
            waitUntilDone:NO];
    // waitUntilDone:等selector执行完 再往下执行
    // wait:NO , 先touches method 再 sayHello
    NSLog(@" touches method ~ ");
}

- (void)sayHello:(id)object
{
    
    NSLog(@"%@------ %@", object , [NSThread currentThread]);
}

Xcode中可见
  • 常驻线程_第1张图片
    image.png

当然,现在的AFN不是上面那么用了,如下

1

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  ···

2

[[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];

你可能感兴趣的:(常驻线程)