iOS 常駐線(xiàn)程如何創(chuàng)建

@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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容