无法识别的选择器已发送到TextAction上的实例

无法识别的选择器已发送到TextAction上的实例

我对此错误有一些疑问:

ProjectName.ViewController textAction:]: unrecognized selector sent to instance 0x7fa60bc3840


当我尝试创建警报时出现错误。这是代码:

@IBAction func trySearch(sender: UIButton) {
    self.api.getUser(self.textField.text!) { isResponse in
        if (isResponse.count == 0) {
//Still crash HERE.
            let alert = UIAlertController(title: "Error", message: "This username doesn't exist", preferredStyle: UIAlertControllerStyle.Alert)
                alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
        else {
            print("existing username")
        }
    }


如果我注释所有警报代码并用简单的打印内容替换它,那么它就起作用了……我真的不明白为什么……谢谢!

getUser函数:

func getUser(user: String, completion: ((isReponse: AnyObject) -> Void)) {

    let request = NSMutableURLRequest(URL: NSURL(string: "https://********")!)
    request.HTTPMethod = "GET"
    request.setValue("Bearer \(self.loadToken())", forHTTPHeaderField: "Authorization")

    Alamofire.request(request)
        .responseJSON { response in
            switch response.result {
            case .Success(let JSON):
                completion(isReponse: JSON)
            case .Failure(let error):
                print("Request failed with error: \(error)")
            }
        }
}


更新:当我单击我的TextField的“完成”时,出现相同的错误。 +我添加了getUser函数。

最佳答案

您可能处在错误的线程中,因为要在一个块中显示警报,请尝试:

dispatch_async(dispatch_get_main_queue(), { _ in
    let alert = UIAlertController(title: "Error", message: "This username doesn't exist", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
})

关于ios - iOs-无法识别的选择器已发送到TextAction上的实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36038736/

10-08 21:07