将数据传递给两个标签栏中的两个视图控制器

Pass data to two view controllers in the two tabbars

我有一个从用户那里获取用户名的登录页面 此登录页面连接到 UITabbarController,其中包含选项卡(viewControllers)。 点击登录按钮后,我通过 prepare segue

将用户名传递给选项卡中的第一个视图
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "profile" { 
        let barViewControllers = segue.destination as! UITabBarController
        let navProfile = barViewControllers.viewControllers![0] as! UINavigationController
        if let profile = navProfile.viewControllers[0] as? ProfilePage {
            profile.username = self.usernameInput.text!.replacingOccurrences(of: " ", with: "")
        }
    }
}

问题是这个用户名也应该传递给第二个标签。我在第一个选项卡

prepare segue 中尝试了它
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "profile" { 
        let barViewControllers = segue.destination as! UITabBarController
        let navProfile = barViewControllers.viewControllers![0] as! UINavigationController
        if let profile = navProfile.viewControllers[0] as? ProfilePage {
            profile.username = self.usernameInput.text!.replacingOccurrences(of: " ", with: "")
        }
        let navTimeline = barViewControllers.viewControllers![1] as! UINavigationController
        if let timeline = navTimeline.viewControllers[1] as? TimelinePage {
            timeline.username = self.usernameInput.text!.replacingOccurrences(of: " ", with: "")
        }
    }
}

但应用程序因此错误而崩溃

index 1 beyond bounds [0 .. 0]

谁能帮我把用户名也传递给第二个标签?

替换

 if let timeline = navTimeline.viewControllers[1] as? TimelinePage {

 if let timeline = navTimeline.viewControllers.first as? TimelinePage {

由于导航只有 1 个 vc 所以索引 1 会崩溃


此外,最好在整个应用程序中共享用户模型的单例 class