iOS GCD常驻线程

- (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后面的代码不会再执行

    };

}

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