Swift:我的destinationVC segue显示为nil

时间:2019-05-30 17:58:48

标签: swift uistoryboardsegue

我正在让用户通过文本字段(名称,电子邮件等)填写一些个人资料信息,这些信息用于设置我的ProfileContoller.shared.profile值。当我进入导航区以传递数据时,我的destinationVC.profile不会将其值设置为发送配置文件对象,而是得到nil。

我的sendingVC嵌入在导航控制器中,而我的destinationVC嵌入在标签栏控制器中。

Segue SendingVC

Attributes Inspector SendingVC

DestinationVC

// Sending View Controller: 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        updateViews()
    }

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}

我的发送对象有数据:     (lldb)po配置文件     设定档:0x600000c873c0

目标对象意外为nil:     (lldb)po destinationVC?.profile     零

3 个答案:

答案 0 :(得分:0)

didSet在尚未加载segue的vc时触发,因此所有出口都为空

您需要将updateViews()放在viewDidLoad


加上您的目的地是一个tabBar

let tab = segue.destination as! UITabBarController
let destinationVC = tab.viewControllers![2] as! ProfileViewController

答案 1 :(得分:0)

我认为您要做的就是在主线程中调用updateViews()

didSet {
        print("did set profile called")
        DispatchQueue.main.async{[weak self] in
            guard let self = self else {
                return
            }
            self.updateViews()
        }
    }

另一种选择是更新viewDidLoad()中的视图

override func viewDidLoad() {
    if let prof = self.profile {
        self.updateViews()
    }
}

答案 2 :(得分:0)

您可以使用以下代码将数据安全地传递到ProfileViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let profile = ProfileController.shared.profile else { return }
        if segue.identifier == "signUpMemicTBC" {
            guard let tabBarController = segue.destination as? UITabBarController else { return }
            guard let profileController = tabBarController.viewControllers?.index(at: 2) as? ProfileViewController else {
                return
            }
            profileController.profile = profile
        }
    }