2012-08-16 152 views
1

我試圖在下面的代碼中使用睡眠,當NSStream連接失敗或者如果有流錯誤並嘗試在睡眠後重新連接。睡眠正在工作,但它使整個應用程序進入睡眠狀態。NSThread的睡眠

我已經將NSStream作爲線程啓動,但是當接收到NSStreamEvent時,handleEvent似乎以同步方式工作。

對於這段代碼使用睡眠的任何想法..?我只想讓睡眠單獨爲Stream線程工作。

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event 
{ 
     case NSStreamEventErrorOccurred: 
     { 
      NSError *streamErr = [stream streamError]; 
      NSString *strErr = [streamErr localizedFailureReason]; 
      [self CloseStream]; 
      NSLog(@"Stream Error ::: %@",strErr); 
      //[NSThread sleepForTimeInterval : 15]; 
      sleep(15); 
      [self Initialize]; 
      [self OpenStream]; 
      break; 
     } 

     case NSStreamEventEndEncountered: 
     { 
      NSLog(@"Connection Closed by the Server"); 
      [self CloseStream]; 
      usleep(15000); 
      [self Initialize]; 
      [self OpenStream]; 
      break; 
     } 
} 

回答

1

您應該使用GCD(Grand Central Dispatch)。您的代碼正在後臺執行,您的應用程序不會凍結。

閱讀本:GCD Reference

基本上你創建隊列和添加的代碼塊,這是在後臺執行。這裏是我的代碼示例

dispatch_queue_t backgroundQueue = dispatch_queue_create("some_identifier", NULL); 
dispatch_async(backgroundQueue, ^(void) { 
     //do your background stuff 

     dispatch_sync(dispatch_get_main_queue(), ^{ 
      //update the gui (if needed) 
     }); 

    }); 
+1

不要忘記dispatch_release :) – jjxtra 2013-01-26 06:06:05