iOS GCD常驻线程

2021-03-08  本文已影响0人  李十岁

- (void)viewDidLoad {

    [super viewDidLoad];

    [self performSelector:@selector(testtest) onThread:[ViewController shareThread] withObject:nil waitUntilDone:YES];

}

- (void)testtest {

    NSLog(@"%@",[NSThread currentThread]);

}

+ (NSThread *)shareThread {

    staticNSThread* shareThread =nil;

    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

        shareThread = [[NSThread alloc] initWithTarget:self selector:@selector(test) object:nil];

        [shareThreadstart];

        [shareThreadsetName:@"常驻线程测试"];

        NSLog(@"%@",[NSThread currentThread]);// 这里还是主线程 假如在这加入到runloop中不会生效

    });

    returnshareThread;

}

+ (void)test{

    // 加入到runloop中必须在自己的线程中加入

    @autoreleasepool {

        NSRunLoop * runloop = [NSRunLoop currentRunLoop];

        [runloopaddPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];

        [runlooprun];

        // run后面的代码不会再执行

    };

}

上一篇下一篇

猜你喜欢

热点阅读