iOs - 在TextAction上发送到实例的无法识别的选择器

时间:2016-03-16 14:34:32

标签: ios iphone ios9 alert

我遇到这个错误的一些问题:

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函数。

2 个答案:

答案 0 :(得分:0)

您可能在错误的帖子中,因为您在一个区块内呈现警报,请尝试:

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)
})

答案 1 :(得分:-1)

处理程序 用户选择操作时要执行的块。此块没有返回值,并将选定的操作对象作为其唯一参数。 你不在这里指定行动。 像这样:

UIAlertAction* ok = [UIAlertAction
                 actionWithTitle:@"OK"
                 style:UIAlertActionStyleDefault
                 handler:^(UIAlertAction * action)
                 {
                     //Do some thing here
                     [view dismissViewControllerAnimated:YES completion:nil];

                 }];
// add action to your alertController

[alert addAction:ok];

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertAction_Class/#//apple_ref/occ/clm/UIAlertAction/actionWithTitle:style:handler