iOS开发中,新创建的线程,执行完成后会销毁,如何让线程常驻内存
- (void)creadResidentThread
{
_listenThread = [[NSThread alloc] initWithTarget:self selector:@selector(listening) object:nil];
[_listenThread start];
}
- (void)listening
{
@autoreleasepool {
[[NSThread currentThread] setName:@"listeningThread"];
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
//加入timer/port保证线程不会没有源而退出
[runloop addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
//默认线程的runloop没有启动,需要手动启动
[runloop run];
}
}
//调用
[self performSelector:@selector(test) onThread:self.listenThread withObject:nil waitUntilDone:NO];
使用场景