swift - 填充 tableview 时,我的应用程序崩溃,因为它声称某个属性为 nil,但在我设置它之前打印该属性说它有一个值

标签 swift uitableview firebase swift3 uisearchbar

我正在使用搜索栏搜索用户名数据库,并相应地更新 TableView 的 User() 数据库。搜索可以很好地更新数组,但是当我尝试将自己的标签更改为 User() 的名字时,我的应用程序崩溃了,因为它声称 firstName 为 nil。不过,我知道事实并非为零。在尝试更新标签之前,我打印了对象的属性并打印了正确的用户名。我不知道我做错了什么。这是代码...

class AddFriendsVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var profiles = [User]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
    searchBar.delegate = self
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return profiles.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? FriendCell {
        let friend = profiles[indexPath.row]
        print(friend.firstName)  //PRINTS THE USERNAME...
        cell.nameLabel.text = friend.firstName //CRASHES HERE. firstName is of type "String!"
        return cell
    }
    return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    DataService.dataService.REF_USERNAMES.queryOrderedByKey().queryStarting(atValue: searchText).queryEnding(atValue: searchText+"\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in

        if snapshot.exists() {
            var results = [User]()
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for snap in snapshots {
                    print(snap.key)
                    let result = User(first: "\(snap.key)", last: "s", username: "s", activeTrip: "s")
                    results.append(result)

                    if snap == snapshots.last {
                        self.profiles = results
                        print(self.profiles[0].firstName) //PRINTS CORRECT USERNAME
                        self.tableView.reloadData()
                    }
                }
            }

        }
    })
}  
}

每次我打印数据时,用户名都在那里...为什么这不起作用?

最佳答案

问题不在于 friend.firstName 而在于 cell.nameLabelIBOutlet 是隐式展开的可选值,在本例中是 UILabel!,这意味着如果它们没有正确连接,它们将是 nil 并且像你看到的那样崩溃。确保该属性已连接到类并且应该修复。

关于swift - 填充 tableview 时,我的应用程序崩溃,因为它声称某个属性为 nil,但在我设置它之前打印该属性说它有一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335589/

相关文章:

JSON 提要不会显示在 Tableview 中

variables - 在服务 worker (Firebase) 中设置变量 messagingSenderId

android - FirebaseRemoteConfig getString 返回空但远程配置的字节数组不为空

ios - 将 deviceToken 保存到 NSUserDefaults

ios - 修复覆盖函数 viewDidAppear

swift - 调用中的额外参数,便利初始化器

javascript - 在检索数据期间对对象进行分组

ios - 将图片放入 DynamoDB

ios - 将一个数组类型的解析对象设置为 tableView

ios - UITableViewSource 单元格高度始终为 44 点