Swift 填充tableview时,我的应用程序崩溃,因为它声称某个属性为零,但在设置该属性之前打印该属性表示它有值
我正在用搜索栏搜索用户名数据库,并相应地更新tableview的User()数据库。搜索会很好地更新数组,但当我发现tableview试图将自己的标签更改为用户的名字()时,我的应用程序崩溃,因为它声称名字为零。不过,我知道这不是零。就在它尝试更新标签之前,我打印了对象的属性,它打印了正确的用户名。我不知道我做错了什么。这是密码Swift 填充tableview时,我的应用程序崩溃,因为它声称某个属性为零,但在设置该属性之前打印该属性表示它有值,swift,uitableview,firebase,swift3,uisearchbar,Swift,Uitableview,Firebase,Swift3,Uisearchbar,我正在用搜索栏搜索用户名数据库,并相应地更新tableview的User()数据库。搜索会很好地更新数组,但当我发现tableview试图将自己的标签更改为用户的名字()时,我的应用程序崩溃,因为它声称名字为零。不过,我知道这不是零。就在它尝试更新标签之前,我打印了对象的属性,它打印了正确的用户名。我不知道我做错了什么。这是密码 class AddFriendsVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UI
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.namelab
IBOutlet
s是隐式展开的选项,在本例中,UILabel
,这意味着如果它们连接不正确,它们将nil
,并像您看到的那样崩溃。确保属性已连接到类,并且应该进行修复。错误说明了什么?它是否真的说问题出在firstName
上?它说“致命错误:在展开可选值时意外发现nil”,并突出显示该行。还可能是什么?我从上面的IBOutlet
s中看到您正在使用故事板,这意味着cell.namelab
可能是一个outlet,因此类型为UILabel代码>。我猜插座没有正确连接,所以namelab
是零。是的,就是这样。为它重新制作了另一个单元,它工作了,很好的洞察力。如果你想用真实的答案回答,我会把它标记为正确!谢谢,很高兴它成功了!