You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift开发:调用searchUsersWithQuery时出现未识别选择器错误

问题:Swift调用Firestore搜索用户时触发未识别选择器异常

我是Swift新手,尝试通过用户名搜索Firestore数据库中的用户时,遇到以下崩溃错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ToDo.FriendsViewController searchUsersWithQuery:completion:]: unrecognized selector sent to instance 0x107436360'

我原以为问题出在Firestore查询代码db2.collection("users").whereField("userName", isEqualTo: usernameSearched).getDocuments { (querySnapshot, error) in,以下是我的完整代码,请问该异常出现的原因是什么?

class FriendsViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet var searchTextField : UITextField?
    let db = Firestore.firestore()
    let userID = Auth.auth().currentUser?.uid
    
    func addFriend(userID: String, friendID: String) {
        let userRef = db.collection("users").document(userID)
        userRef.updateData(["friends": FieldValue.arrayUnion([friendID])])
    }
    @IBAction func searchButtonTapped(_ sender: Any) {
        guard let usernameSearched = searchTextField?.text else {
            print("error")
            return
        }
        searchUsers(usernameSearched) { users in
            print("Users found: \(users)")
        }
    }

    func searchUsers(_ usernameSearched: String, completion: @escaping ([User]) -> Void) {
        let db2 = Firestore.firestore()
        db2.collection("users").whereField("userName", isEqualTo: usernameSearched).getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Error getting docs: \(error.localizedDescription)")
                completion([])
                return
            }
            var users: [User] = []
            for document in querySnapshot!.documents {
                let data = document.data()
                let email = data["email"] as? String ?? ""
                let profileImageURL = ""
                let user = User(email: email, profileImageURL: profileImageURL)
                users.append(user)
            }
            completion(users)
        }
    }

异常原因分析

这个崩溃的核心是方法调用签名与实际定义不匹配:

  • 你当前定义的搜索方法是searchUsers(_ usernameSearched: String, completion: @escaping ([User]) -> Void),第一个参数没有外部标签,直接用下划线省略。
  • 但错误信息显示程序在尝试调用searchUsersWithQuery:completion:这个方法——这个方法在你的FriendsViewController里根本不存在。

可能的触发场景:

  1. Storyboard/XIB中,搜索按钮的IBAction关联了旧的searchUsersWithQuery:completion:方法,而非当前的searchButtonTapped。
  2. 代码中存在未展示的其他调用逻辑,误用了searchUsersWithQuery这个不存在的方法名。
  3. 旧代码缓存未清理,导致运行时仍尝试调用已删除的方法。

另外说明:你贴出的Firestore查询代码本身没有语法问题,不是这次崩溃的原因。

内容的提问来源于stack exchange,提问作者walkman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:33:23