Ios 使用Prepareforsegue将数据传递给segued控制器,发现无
我要上下面的课Ios 使用Prepareforsegue将数据传递给segued控制器,发现无,ios,swift,Ios,Swift,我要上下面的课 class FriendsProfileViewController: UIViewController { var user : User! override func viewDidLoad() { super.viewDidLoad() print(user.firstName) } } 在segueing类中,我执行了以下操作来传递数据 var friends: [User]? override func ta
class FriendsProfileViewController: UIViewController {
var user : User!
override func viewDidLoad() {
super.viewDidLoad()
print(user.firstName)
}
}
在segueing类中,我执行了以下操作来传递数据
var friends: [User]?
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("viewFriend", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationVC = segue.destinationViewController
if let friendsProfileVC = destinationVC as? FriendsProfileViewController{
if let indexPath = sender as? NSIndexPath{
print(indexPath.row)
friendsProfileVC.user = friends?[indexPath.row]
}
}
}
为什么我会出现错误致命错误:在展开可选值时意外发现nil
即使我的
friend?[indexPath.row]
在我选择时被验证为包含一个值 在执行segue之前尝试获取用户,并将其作为segue发送方传递
var friends: [User]?
private func friend(at index: Int) -> User? {
return friends.flatMap { $0.indicies.contains(index) ? $0[index] : nil }
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let friend = friend(at: indexPath.row) {
performSegueWithIdentifier("viewFriend", sender: friend)
} else {
print("Invalid index: \(indexPath.row)")
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch (segue.destinationViewController, sender) {
case (let controller as FriendsProfileViewController, let user as User):
controller.user = user
default:
break
}
}
我相信的问题是,我们总是从数组中得到一个可选的
friends![indexPath.row]
返回了一个可选(用户)
最后,我将一个可选的用户作为发送者传递了这个消息。打开它并将其设置为我的其他VC
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("viewFriend", sender: friends![indexPath.row])
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print(sender)
let destinationVC = segue.destinationViewController
if let friendsProfileVC = destinationVC as? FriendsProfileViewController{
if let friend = sender as? User{
print(friend)
print(friend.firstName)
friendsProfileVC.user = friend
}
}
}
更新,我已尝试将
friendsProfileVC.user=friends?[indexath.row]
更改为friendsProfileVC.user=friends![indexPath.row]
它成功了。不确定为什么之前它不工作。您调试过吗?如果是,发生了什么?您在哪一行面临给定代码的崩溃??并且您的已初始化或为空??您是否获得了第行打印(indexath.row)
的控制台输出?这意味着您正在传递用户的nil值。你应该选择User的可选值,或者你应该确保你没有传递nil值。检查friends
是否为nil