IOS多線程開發

來源:互聯網
上載者:User

標籤:des   style   blog   http   使用   strong   

本文轉載至 http://blog.csdn.net/davidsph/article/details/8171607

 

IOS的多線程,一般分為三種方式: 

1,Thread;
2, Cocoa operations;
3, Grand Central Dispatch (GCD) (iOS4 才開始支援)

下面簡單說明一下:

1:NSThread

  建立方式主要有兩種:


[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];

NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                        selector:@selector(myThreadMainMethod:)
                                        object:nil];
[myThread start]; //啟動線程

 

這兩種方式的區別是:前一種一調用就會立即建立一個線程來做事情;而後一種雖然你 alloc 了也 init了,但是要直到我們手動調用 start 啟動線程時才會真正去建立線程。這種延遲實現思想在很多跟資源相關的地方都有用到。後一種方式我們還可以在啟動線程之前,對線程進行配置,比如設定 stack 大小,線程優先順序。

此外還有一種間接的方式:利用NSObject的方法

performSelectorInBackground:withObject: 來建立一個線程:
[myObj performSelectorInBackground:@selector(myThreadMainMethod) withObject:nil]; //在後台運行某一個方法
其效果與 NSThread 的 detachNewThreadSelector:toTarget:withObject: 是一樣的。

 

2,NSOperation:

    官方解釋:The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task. Because it is abstract, you do not use this class directly but instead subclass or use one of the system-defined subclasses (NSInvocationOperation or NSBlockOperation) to perform the actual task.

並發執行你需要重載如下4個方法

    //執行任務主函數,線程啟動並執行入口函數

    -(void)start 

      //是否允許並發,返回YES,允許並發,返回NO不允許。預設返回NO

   -(BOOL)isConcurrent 

    - (BOOL)isExecuting

    //是否已經完成,這個必須要重載,不然放在放在NSOperationQueue裡的NSOpertaion不能正常釋放。

   - (BOOL)isFinished

   

  比如TestNSOperation:NSOperaion 重載上述的4個方法,

   聲明一個NSOperationQueue,NSOperationQueue *queue = [[[NSOperationQueue alloc ] init]autorelease];

  [queue addOperation:testNSoperation];

  它會自動調用TestNSOperation裡的start函數,如果需要多個NSOperation,你需要設定queue的一些屬性,如果多個NSOperation之間有依賴關係,也可以設定,具體可以參考API文檔。 

 

    (2)非並發執行

   -(void)main

  只需要重載這個main方法就可以了。 


3、 GCD

 

 

dispatch_async(dispatch_queue_t queue,dispatch_block_t block);

async表明非同步運行,block代表的是你要做的事情,queue則是你把任務交給誰來處理了.

 

之所以程式中會用到多線程是因為程式往往會需要讀取資料,然後更新UI.為了良好的使用者體驗,讀取資料的操作會傾向於在後台運行,這樣以避免阻塞主線程.GCD裡就有三種queue來處理。

1. Main queue:

  顧名思義,運行在主線程,由dispatch_get_main_queue獲得.和ui相關的就要使用MainQueue.

2.Serial quque(private dispatch queue)

  每次運行一個任務,可以添加多個,執行次序FIFO. 通常是指程式員產生的.

3. Concurrent queue(globaldispatch queue):

可以同時運行多個任務,每個任務的啟動時間是按照加入queue的順序,結束的順序依賴各自的任務.使用dispatch_get_global_queue獲得.

所以我們可以大致瞭解使用GCD的架構:

1

2

3

4

5

6

7

dispatch_async(getDataQueue,^{

    //擷取資料,獲得一組後,重新整理UI.

    dispatch_aysnc(mainQueue, ^{

    //UI的更新需在主線程中進行

};

}

)

下面 就來總結一下這三種多線程方式的區別吧:

Thread 是這三種範式裡面相對輕量級的,但也是使用起來最負責的,你需要自己管理thread的生命週期,線程之間的同步。線程共用同一應用程式的部分記憶體空間, 它們擁有對資料相同的存取權限。你得協調多個線程對同一資料的訪問,一般做法是在訪問之前加鎖,這會導致一定的效能開銷。在 iOS 中我們可以使用多種形式的 thread:

Cocoa threads: 使用NSThread 或直接從 NSObject 的類方法 performSelectorInBackground:withObject: 來建立一個線程。如果你選擇thread來實現多線程,那麼 NSThread 就是官方推薦優先選用的方式。

Cocoa operations是基於 Obective-C實現的,類 NSOperation 以物件導向的方式封裝了使用者需要執行的操作,我們只要聚焦於我們需要做的事情,而不必太操心線程的管理,同步等事情,因為NSOperation已經為我 們封裝了這些事情。 NSOperation 是一個抽象基類,我們必須使用它的子類。iOS 提供了兩種預設實現:NSInvocationOperation 和 NSBlockOperation。

Grand Central Dispatch (GCD): iOS4 才開始支援,它提供了一些新的特性,以及運行庫來支援多核並行編程,它的關注點更高:如何在多個 cpu 上提升效率。

 

最後,既然說道多線程的開發,難免會在多線程之間進行通訊;

利用NSObject的一些類方法,可以輕鬆搞定。

 

在應用程式主線程中做事情:
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

 

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array

在指定線程中做事情:
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait

 

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array

在當前線程中做事情:

//Invokes a method of the receiver on the current thread using the default mode after a delay.

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

 

performSelector:withObject:afterDelay:inModes:

取消發送給當前線程的某個訊息
cancelPreviousPerformRequestsWithTarget:

 

cancelPreviousPerformRequestsWithTarget:selector:object:

如在我們在某個線程中下載資料,下載完成之後要通知主線程中更新介面等等,可以使用如下介面:- (void)myThreadMainMethod
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // to do something in your thread job
    ...
    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
    [pool release];
}

 

多線程的學習,是一個不斷前進的過程,一起學習一起進步。今後要多注重使用GCD,因為它與block緊密關聯,會是以後的一個趨勢。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.