我有以下课程,我正在试着。
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]
被证实包含了一个值,当我提出错误时。
答案 0 :(得分:0)
在执行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
}
}
答案 1 :(得分:0)
我认为这个问题是我们总是从数组中取回一个Optional friends![indexPath.row]
返回Optional(User)
。
我最终将可选用户作为发件人传递。打开它并将其设置为我的其他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?[indexPath.row]
更改为friendsProfileVC.user = friends![indexPath.row]
,但它确实有效。不知道为什么它早些时候不起作用。