2016-03-15 37 views
0

如何在同一個方法中的語句之前異步執行塊?以相同方法在語句之前異步執行塊

返回總是塊之前執行,但如果提交恆等於

我想座返回之前執行。 我該怎麼辦? 我嘗試dispatch_semaphore_t,但checkVerifyCode在主線程中。 我無法阻止主線程。

-(BOOL)checkVerifyCode 
{ 
__block BOOL commit = NO; 
    [SMSSDK commitVerificationCode:self.verificationNum.text phoneNumber:self.phoneNumber.text zone:@"86" result:^(NSError *error) { 
     if (error) { 
      NSString *errInfo = [error.userInfo objectForKey:@"commitVerificationCode"]; 
      MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 
      [hud setMode:MBProgressHUDModeText]; 
      [hud setLabelText:@"驗證碼輸入錯誤"]; 
      [hud setLabelText:errInfo]; 

      hud.color = [UIColor clearColor]; 
      hud.labelColor = [UIColor colorWithRed:118/255.f green:214/255.f blue:255/255.f alpha:0.8f]; 
      hud.detailsLabelColor = [UIColor colorWithRed:118/255.f green:214/255.f blue:255/255.f alpha:0.8f]; 
      hud.margin = 10.f; 
      hud.yOffset = -100.f; 
      hud.removeFromSuperViewOnHide = YES; 
      [hud hide:YES afterDelay:3]; 
      NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:commit] forKey:@"bool"]; 
      [self performSelectorOnMainThread:@selector(setCommit:) withObject:dict waitUntilDone:NO]; 

     }else 
     { 
      NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:commit] forKey:@"bool"]; 
      [self performSelectorOnMainThread:@selector(setCommit:) withObject:dict waitUntilDone:NO]; 
      commit = YES; 
     } 
    }]; 
return commit; 

} 
+0

爲了讓你的問題得到正確的答案,請你澄清一下,如果方法checkVerifyCode的調用者線程與線程結果相同:^(){...}塊被調用,或者這些線程是不同的。 – DisableR

回答

1

您實際上要求使異步方法同步。並且由於您的checkVerifyCode方法調用位於主線程中,因此需要阻塞主線程(如前所述,這是個不好的主意)。

相反,您應該移動到某個地方,您可以根據異步方法的結果調用更新。

即:

  • 搭建進度指示器和寫着「檢查你的代碼」
  • 修改checkVerifyCode在異步調用的最後返回void
  • 場,地方調用一些方法:

_

[self _checkVerifyDone:commit]; 

而且,如果你真的需要它的主隊列:

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self _checkVerifyDone:commit]; 
}); 
0

您可以調度整個函數到一個單獨的隊列,然後使用dispatch_semaphore,直到返回結果,以阻止該隊列。

這裏你的更高層次的目標是什麼?看起來您可能正在尋找dispatch_notify_group,但很難從您的問題中得知。我明白你想要解決的問題,但是大局是什麼?

0

而不是返回值「提交」像你正在做什麼,傳遞到方法完成塊,需要一個「布爾」作爲一個參數。然後調用者將能夠將代碼傳遞給'verifyCheckCode'並使其異步執行。

相關問題