IOS瘋狂基礎之多線程編程NSThread

關於等待

            returnData=[[myhttp.resultsDictionary valueForKey:@"body"] valueForKey:@"list"];

            while (!returnData) {

                returnData = [[myhttp.resultsDictionary valueForKey:@"body"] valueForKey:@"list"];

                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

            }



 iOS有三種多線程編程的技術,分別是:

1.、NSThread 

2、Cocoa NSOperation (iOS多線程編程之NSOperation和NSOperationQueue的使用

3、GCD  全稱:Grand Central Dispatch( iOS多線程編程之Grand Central Dispatch(GCD)介紹和使用

這三種編程方式從上到下,抽象度層次是從低到高的,抽象度越高的使用越簡單,也是Apple最推薦使用的。


NSThread:

優點:NSThread 比其他兩個輕量級

缺點:需要自己管理線程的生命週期,線程同步。線程同步對數據的加鎖會有一定的系統開銷


NSThread 有兩種直接創建方式

//1.直接創建線程並且開始運行線程
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];

//2.先創建線程對象,然後再運行線程

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:)  object:nil];  

[myThread start];  



  1. -(void)downloadImage:(NSString *) url{  
  2.     NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];  
  3.     UIImage *image = [[UIImage alloc]initWithData:data];  
  4.     if(image == nil){  
  5.           
  6.     }else{  
  7. //通知主線程
  8.         [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];  
  9.     }  

關於 waitUntilDone

- (void)changePopoverSize

{

    [self performSelectorOnMainThread:@selector(changeText:) withObject:@"Happy aha111" waitUntilDone:YES];

    NSLog(@"changePopoverSize#####end");

    sleep(5);

    NSLog(@"changePopoverSize-----end");

}

執行結果如下:


2012-08-17 17:19:29.618 awrbv[2024:f803] changeText:(NSString *)string

2012-08-17 17:19:29.619 awrbv[2024:f803] changePopoverSize#####end

2012-08-17 17:19:34.620 awrbv[2024:f803] changePopoverSize-----end

可以看出,如果waitUntilDone:YES那麼等changeText執行完畢後再往下執行

如果waitUntilDone:NO的話,結果如下:


2012-08-17 17:21:12.135 awrbv[2049:f803] changePopoverSize#####end

2012-08-17 17:21:17.137 awrbv[2049:f803] changePopoverSize-----end

2012-08-17 17:21:17.139 awrbv[2049:f803] changeText:(NSString *)string



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