IOS多線程(NSThread,NSOperation,Grand Central Dispatch)

來源:互聯網
上載者:User

標籤:style   color   io   os   使用   ar   strong   for   資料   

•NSThread:

  –優點:NSThread 比其他兩個輕量級,使用簡單  –缺點:需要自己管理線程的生命週期、線程同步、加鎖、睡眠以及喚醒等。線程同步對資料的加鎖會有一定的系統開銷 •NSOperation:

   –不需要關心線程管理,資料同步的事情,可以把精力放在自己需要執行的操作上

   –NSOperation是物件導向的

   - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

•如果要更新UI介面,可以在後台線程中調用performSelectorOnMainThread方法 •提示:儘管使用performSelectorInBackground方法調用的任務可以更新UI介面,但是在實際開發中,涉及到UI介面的更新操作,還是要使用performSelectorOnMainThread   方法,以避免不必要的麻煩 •開啟後台執行任務的方法   -(void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg •在後台線程中通知主線程執行任務的方法   –(void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait; •擷取線程資訊   [NSThread currentThread]; •線程休眠   [NSThread sleepForTimeInterval:1.0f];   + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument; - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;•detachNewThreadSelector方法會直接啟動線程方法•initWithTarget需要調用start方法才能夠啟動線程方法•參數說明:  –selector:線程執行的方法,只能有一個參數,不能有傳回值  –target:selector訊息發送的對象  –argument:傳輸給target的唯一參數,也可以是nil •NSOperation的兩個子類  1.NSInvocationOperation  2.NSBlockOperation•工作原理:  1.用NSOperation封裝要執行的操作  2.將建立好的NSOperation對象放NSOperationQueue中  3.啟動OperationQueue開始新的線程執行隊列中的操作•注意事項:  1.使用多線程時通常需要控制線程的並發數,因為線程會消耗系統資源,同時啟動並執行線程過多,系統會變慢  2.使用以下方法可以控制並發的線程數量:-(void)setMaxConcurrentOperationCount:(NSInteger)cnt;

IOS多線程(NSThread,NSOperation,Grand Central Dispatch)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.