? ?在iOS開發中,線程的創建與管理已經被Apple進行了很好的封裝,但是在開發者實際開發中會濫用GCD,導致整個代碼混亂不堪,因此在這里需要對iOS開發中的多線程開發進行整理。
1.? 主線程完成耗時操作,會導致UI卡頓,因此耗時操作要以子線程的運行方式來運行
? ? ?在iOS的Framework Controller中重載的與UI相關的方法都是在主線程中完成的,因此如果有需要從網絡下載數據的方法,需要切換到子線程中進行,并且在數據下載完成后需要更新UI,這個時候又需要在主線程中更新UI
2.創建Thread方法
? ?(1)pthread方法
? ? ? ? ?pthread是操作系統C語言接口,非常底層,一般很少使用
? ? ? ? pthread_t
? ? ? ? pthread_create
? ? ?(2)NSThread方法
? ? ? ? NSThread是IOS框架封裝的線程對象,需要自己管理線程的生命周期
? ? ? ? 一個線程一般分為:創建, 就緒, 運行,掛起,消亡
? ? ? ?create ready running suspend dead
? ? ? ? 創建一個NSThread的方法:
? ? ? ? NSThread *thread = [[NSThreadalloc] initWithTarget:selfselector:@selector(downLoad:)object:@"http://1.png"];
? ? ? ?[thread start]
? ? ? ?[NSThreaddetachNewThreadSelector:@selector(downLoad:)toTarget:selfwithObject:@"http://2.png"];
? ? ? ?[self performSelector:@selector(downLoad:) onThread:[NSThread currentThread] withObject:@"http://3.png"waitUntilDone:NO];
? ? ? ?[self ?performSelectorInBackground:@selector(downLoad:) withObject:@"http://3.png"];
? ?(3)線程安全
線程安全? 加鎖-一定要對片段代碼進行枷鎖
@synchronized(self)? {
}?
? ??
(4)線程間的通信
在子線程中進行加載網絡數據
在主線程中進行刷新UI
? ?
1.? GCD
Dispatch_queue_t
Dispatch_get_global_queue
?
Dispatch_queue_create();
在主線程接受用戶的輸入事件
在線程執行耗時下載操作
然后再回到主線程中更新UI
默認主隊列為串行執行
默認的全局隊列為并行執行
??
? ? ? ?