你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> ios 開發中的多線程

ios 開發中的多線程

編輯:IOS開發綜合

iOS中使用多線程的原因:

1,iOS中只有主線程有直接修改Ui的權利

2,iPhone中主線程堆棧1M,新開辟的線程堆棧512K

3,多任務,多核,效率,用戶體驗共同決定


(一)GCD(Grand Central dispatch)block和dispatch,可以簡化多核多線程編程,iOS4以後支持

1,block的定義類似於函數指針;block對象(塊對象);

可以存在block數組;

但block存儲在函數棧中,注意大括號中的生命周期;

2,block典型用法,圖片下載應用中的塊應用,嵌套異步block塊的使用,如果前面ok,則去UI更新

dispatch_async(dispatch_queue_create("com.enormego.EGOImageLoader",NULL), ^{

UIImage* image = styler(anImage);

[[EGOCache currentCache] setImage:image forKey:keyForURL(aURL, style) withTimeoutInterval:604800];

dispatch_async(dispatch_get_main_queue(), ^{

completion(image, aURL, nil);

});

});


(二)NSOperation和NSOpertionQueue

1,一個繼承自NSOperation的操作類,該類的實現中必須有 (void) main()方法

2,最簡單的方法,將NSOperation的實例放入NSOpertionQueue中

3,可以在NSOpertionQueue中設置同時可以進行的操作數

(三)NSThread

1,detachNewThreadSelector此為簡便方法,不用進行線程清理

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


2,NSThread initialWithTarget, (void)start;方法,可以創建線程,但選擇合適的時機啟動線程

NSThread* myThread = [[NSThread alloc] initWithTarget:self

selector:@selector(myThreadMainMethod:)

object:nil];

[myThread start];


(四)線程間同步

1,原子鎖屬性,automic,noautomic,變量可以保證多線程訪問

2,NSCondition,可以提供帶條件的同步鎖,解鎖時,需要輸入相同的條件才能解鎖

3,NSLock, lock,unlock比較簡單的同步鎖

4,@synchronized(anObject)更簡單的所方式,通常用在單例對象的創建上面

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved