@interface ViewController ()
@property (nonatomic,strong) NSThread *thread;
@end
@implementation ViewController
-(void)viewDidLoad{
? ? [super viewDidLoad];
? ? self.view.backgroundColor = [UIColor whiteColor];
? ? //獲取這個(gè)常駐內(nèi)存的線(xiàn)程
? ? self.thread=? [ViewController longTermThread];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
? ? //在該線(xiàn)程上提交任務(wù)
? ? [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
}
-(void)test{
? ? NSLog(@"test");
? ? NSLog(@"%@",[NSThread currentThread]);
}
+ (void)entryPoint
{
? ? //設(shè)置當(dāng)前線(xiàn)程名為MyThread
? ? [[NSThread currentThread] setName:@"MyThread"];
? ? //獲取NSRunLoop對(duì)象,第一次獲取不存在時(shí)系統(tǒng)會(huì)創(chuàng)建一個(gè)
? ? NSRunLoop*runloop = [NSRunLoopcurrentRunLoop];
? ? /*
?? ? 添加一個(gè)Source1事件的監(jiān)聽(tīng)端口
?? ? RunLoop對(duì)象會(huì)一直監(jiān)聽(tīng)這個(gè)端口,由于這個(gè)端口不會(huì)有任何事件到來(lái)所以不會(huì)產(chǎn)生影響
?? ? 監(jiān)聽(tīng)模式是默認(rèn)模式,可以修改為Common
?? ? */
? ? [runloopaddPort:[NSPort port] forMode:NSDefaultRunLoopMode];
? ? //啟動(dòng)RunLoop
? ? [runlooprun];
}
+ (NSThread*)longTermThread
{
? ? //靜態(tài)變量保存常駐內(nèi)存的線(xiàn)程對(duì)象
? ? staticNSThread*longTermThread =nil;
? ? //使用GCD dispatch_once 在應(yīng)用生命周期只執(zhí)行一次常駐線(xiàn)程的創(chuàng)建工作
? ? staticdispatch_once_tonceToken;
? ? dispatch_once(&onceToken, ^{
? ? ? ? //創(chuàng)建一個(gè)線(xiàn)程對(duì)象,并執(zhí)行entryPoint方法
? ? ? ? longTermThread = [[NSThreadalloc]initWithTarget:selfselector:@selector(entryPoint)object:nil];
? ? ? ? //啟動(dòng)線(xiàn)程,啟動(dòng)后就會(huì)執(zhí)行entryPoint方法
? ? ? ? [longTermThreadstart];
? ? });
? ? returnlongTermThread;
}
@end