iOS學習筆記--02 多線程

iOS的有三種多線程技術:

(一)NSThread
(二)Cocoa Operation
(三)GCD(全稱:Grand Central Dispatch
以上三種技術,抽象程度從低到高。抽象程度越高,當然使用起來越簡單好用。後者也是蘋果較爲推薦的方式。

(一)NSThread

兩種實現方式:
1)實例方法

- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullableid)argument;

2)類方法

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullableid)argument;


ps:所謂的實例方法,就是需要實例化一個對象,使用該對象進行調用。而類方法則直接使用類名調用的方式。

參數的意義:
selector :線程執行的方法,這個selector只能有一個參數,而且不能有返回值。
target  :selector消息發送的對象
argument:傳輸給target的唯一參數,也可以是nil
 
第一種方式是先創建線程對象,然後再運行線程操作,在運行線程操作前可以設置線程的優先級等線程信息;
第二種方式會直接創建線程並且開始運行線程。

下面是兩種方式的實現示例:
1)實例方法實現:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(doSomething) object:nil];
    [myThread start];
}
-(void)doSomething{
    NSLog(@"新線程:%@",[NSThread currentThread]);
}

2)類方法實現:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"主線程%@",[NSThread currentThread]);
    [NSThread detachNewThreadSelector:@selector(doSomething) toTarget:self withObject:nil];
}
-(void)doSomething{
    NSLog(@"新線程:%@",[NSThread currentThread]);
}

下面是下載圖片的例子:
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIImageView *myImageView;

@end

#import "ViewController.h"
#define imgUrl @"http://c.hiphotos.baidu.com/image/w%3D310/sign=4b3d50d58813632715edc432a18ea056/d52a2834349b033b015730d317ce36d3d439bdd8.jpg"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(downLoadImg) object:nil];
//    [myThread start];
    NSLog(@"主線程%@",[NSThread currentThread]);
    [NSThread detachNewThreadSelector:@selector(downLoadImg) toTarget:self withObject:nil];
}
-(void)downLoadImg{
    NSLog(@"新線程:%@",[NSThread currentThread]);
    NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imgUrl]];
    UIImage *image = [[UIImage alloc]initWithData:data];
    if (image) {
        //通知主線程更新UI
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
    }
}
-(void)updateUI:(UIImage*)image{
    self.myImageView.image = image;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

其中,線程間的通訊:通知主線程更新UI
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
除了更新主線程,也可以指定其他線程:
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;




未完待續。


參考:http://www.cocoachina.com/industry/20140520/8485.html
說明:本筆記作爲學習記錄用,無意侵權。所有引用皆會在參考處說明。












發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章