0

I recently converted an app from individual controllers to a UITabBar application. In this app I need to pass data from tab1-ViewController to tab2-ViewController, I used to do it through delegation but now the way I'm doing it's by accessing the properties from tab1 in tab2 and setting them directly there.

Is this considered a bad practice? If yes, what is the most common way to pass data between tabs in a UITabBarController app?

Here is the code...

Tab1 ViewController

class Tab1ViewController: UIViewController{
    var name:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()

        /// Do something with name
    }
}

Tab2 ViewController

class Tab2ViewController: UIViewController{

    override func viewDidLoad() {
            let tab1VC = self.tabBarController?.viewControllers?[0] as! Tab1ViewController
            tab1VC.name = "John"
    }
}
Apurv
  • 17,116
  • 8
  • 51
  • 67
fs_tigre
  • 10,650
  • 13
  • 73
  • 146

2 Answers2

1

You could subclass the UITabBarController.It would be easy to access from multiple view controllers

But as my quick research @Woodster says

Keep in mind that when you pass an array in Swift, you're passing it by value, unlike Objective-C, which passes it by reference. This means that changes made by your second view controller won't be reflected in your first view controller, because your second one is using a copy of the array, not the same array. If you want both view controllers to modify the same array, put the array in a class, and pass a single instance of that class around.

As of my knowledge the bad practice in your code is directly unwrapping values.like below

 let tab1VC = self.tabBarController?.viewControllers?[0] as! Tab1ViewController
Dharma
  • 3,007
  • 3
  • 23
  • 38
  • Thank you for the link, I also found this article: https://makeapppie.com/2015/02/04/swift-swift-tutorials-passing-data-in-tab-bar-controllers/. I agree, I should be using `if let`. – fs_tigre Jun 21 '17 at 13:40
1

I think delegate is the best way. You need to be careful when you directly setting properties like this. Since you force unwrapping the controller, it will break when the controller is null. And in tab controller, if you display tab2 by default, then tab1 will be null unless you click on it.

Other than that, if you just want to pass properties, I think its okay to pass it in this way. Just use if let to make sure that your code at least won't crash.

Fangming
  • 24,551
  • 6
  • 100
  • 90