常駐線程有什么用呢教寂?
讓一個(gè)一直存在的子線程钢猛,等待其他線程發(fā)來(lái)消息锈嫩,處理其他事件待逞。
1.設(shè)置成全局的甥角,如果是線程對(duì)象是局部的就會(huì)死掉
@property (nonatomic,strong) NSThread *thread;
2.初始化線程并啟動(dòng)
self.thread = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
[self.thread start];
3.啟動(dòng)RunLoop,子線程的RunLoop默認(rèn)是停止的
- (void)run{
//只要往RunLoop中添加了 timer识樱、source或者observer就會(huì)繼續(xù)執(zhí)行嗤无,一個(gè)Run Loop通常必須包含一個(gè)輸入源或者定時(shí)器來(lái)監(jiān)聽(tīng)事件,如果一個(gè)都沒(méi)有怜庸,Run Loop啟動(dòng)后立即退出当犯。
@autoreleasepool {
//1、添加一個(gè)input source
[[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
//2割疾、添加一個(gè)定時(shí)器
// NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
// [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
// [[NSRunLoop currentRunLoop] run];
}
}
這樣thread
這個(gè)線程就會(huì)一直存在嚎卫,當(dāng)需要使用此線程在處理一些事情的時(shí)候就這么調(diào)用
4.利用常駐線程處理事情
[self performSelector:@selector(action) onThread:self.thread withObject:nil waitUntilDone:NO ];
在action方法中 寫(xiě)下你需要處理事情的代碼即可。