2016-11-05 39 views
0

我有一個自定義的UIView控制器初始化我像這樣:使用封閉傳遞給函數會導致一個malloc崩潰

inputPhoneNumberView.frame = CGRect(x: 0, y: 0, width: 286, height: 73) 
let alert = SAAlertView(title: "Enter Your Phone Number", message: "Enter or update your phone number and we will send you a verification code via SMS.", customView: inputPhoneNumberView) 
alert.addAction("Confirm", style: .default, dismissAfterAction: false, hasLoadingIndicator: true) {() -> Void in 
    print("Hello!") //Testing code 
} 
alert.addAction(NSLocalizedString("cancel", comment: ""), style: .cancel, actionBlock: nil) 
present(alert, animated: true, completion: nil) 

動作可以被添加到被關聯到裏面UIButtons視圖控制器。例如alert.addAction(NSLocalizedString("cancel", comment: ""), style: .cancel, actionBlock: nil

動作是定義爲這樣一個結構:

struct Action { 
     var title: String 
     var style: ActionStyle 
     var actionBlock: (() -> Void)? 
     var dismissAfterAction: Bool 
     var hasLoadingIndicator: Bool 
    } 

在動作的代碼塊是在該方法中處理的:

fileprivate dynamic func doAction(_ sender: CustomButton) { 

     // Make sure the action should be allowed for default only. 

     let action = actions[sender.tag] 

     guard sender.tag >= 0 && sender.tag < actions.count else { 
      print("No action at that index.", logType: .Error) 
      return 
     } 

     if let block = action.actionBlock { 
      if action.dismissAfterAction { 
       dismiss(animated: true, completion: { 
        block() 
       }) 
      } else { 

       block() // The point the crash occurs! 
      } 
     } else { 
      dismiss(animated: true, completion: nil) 
     } 
    } 

有創建一個動作dismissAfterAction當一個選項即自動關閉視圖控制器,然後執行代碼塊。但是,如果dismissAfterActionfalse該應用程序將崩潰與malloc error。它並不總是崩潰,但如果我反覆點擊與該動作關聯的按鈕,它最終會。不知道這裏發生了什麼。有沒有人遇到過這樣的事情?似乎是代碼塊的問題。

+0

您可以發佈任何崩潰日誌嗎?我會檢查你在封閉中的實際操作。 –

回答

1

前段時間我可能會遇到問題。作爲修正,您可以通過以下方式更改您的代碼:

 //we already checked action block, so 
     action.actionBlock!() 
     //block() The point the crash occurs! 
+0

哇該作品!爲什麼它工作?爲什麼我不能使用let語句中的'block'? – KexAri

+0

我現在不知道,我應該加入調查堆棧。 – Mikhail