多線程(Multithreading)
隊列(queues)
在iOS中多線程主要是關於“隊列”。隊列中使用“塊”。塊被隊列提取出來,在相關的線程上執行。
主隊列(main queue)
所有的UI活動都必須且只能在在主隊列上執行。
相對地,那些消耗內存的非UI活動必須在其他隊列上執行。
總之,原則是讓UI響應起來。
其他的隊列
多數情況下,iOS幫我們建立好了其他的隊列。
1.兩種方式建立主隊列
dispatch_queue_t mainQ = dispatch_get_main_queue();
NSOperationQueue *mainQ = [NSOperationQueue mainQueue];
2.建立其他隊列
dispatch_queue_t otherQ = dispatch_queue_create(“name”, NULL);//name是字符型常量
3.在主隊列上調用方法
- (void)performSelectorOnMainThread:(SEL)aMethod
withObject:(id)obj
waitUntilDone:(BOOL)waitUntilDone; dispatch_async(dispatch_get_main_queue(), ^{ /*調用的方法 */ });
4.多線程示例
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL urlWithString:@“http://...”]];
NSURLConfiguration *configuration = …;
//下面在主隊列上建立session,這樣就可以在task中處理UI
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask *task;
task = [session downloadTaskWithRequest:request
completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
/* 可以在此處處理UI/ }];
//如果要在此處處理一些非UI進程,最好很快, 千萬不要阻礙主隊列!
[task resume];
當然,如果session不在主隊列,而你想做一些UI的事情,那麼可以在主隊列上使用“塊”。
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; //不在主隊列上
NSURLSessionDownloadTask *task;
task = [session downloadTaskWithRequest:request
completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{ /* do UI things */ });
or [self performSelectorOnMainThread:@selector(doUIthings) withObject:nil waitUntilDone:NO];
}];
[task resume];