2

I'm a beginner working on swift. So in my project I have used multiple object/model, which I have used in almost all the controllers. My question is, how do I update my object/model(across all the controller)automatically when it is updated in any one of the controller?

What would be the correct way of performing this and how would I go about it??

Raj.S
  • 81
  • 1
  • 2
  • 9
  • 1
    you should add observers for your objects in controllers, and implement methods update your viewController UI – Alexandr Kolesnik Dec 29 '17 at 10:41
  • If the same model is used everywhere, why not have a singelton object of that model. This way no matter where you modify this the changes can ge obtained in all controllers. Do this only if you are sure of the requirement as this might cause untraceable bugs.. – Rakshith Nandish Dec 29 '17 at 10:50
  • Can you just update some codes like how you're creating model , using your model object and updating model? – Arun Kumar Dec 29 '17 at 10:57

1 Answers1

0

There is concept of Pass By Value & Pass By Reference.

Best fit solution for your question is to use Pass By Reference type.

If we talk about Swift programming language.

class are Reference type & struct are Value type.

So, your model class should be build up with class type.

Code example.

class Dog {
    var breed : String = ""
    var sub_breed = [String]()
    init(_breed:String,_sub_breed:[String]) {
        self.breed = _breed
        self.sub_breed = _sub_breed
    }
}

FirstViewController:

var dogs : [Dog] = [Dog(_breed: “Original”, _sub_breed: [“subBreedType1”, “subBreedType2”])]

SecondViewController: // You are passing reference of dogs to SecondVC

var dogs : [Dog] = []

dogs[0].breed = “Modified”

Now you have changed value of breed name from SecondViewController, if you go back to FirstViewController and check the first element of array the value will be “Modified”

You can try this idea.

Other solutions : Singleton object of your Model class.

Thank you.

Rashesh Bosamiya
  • 609
  • 1
  • 9
  • 13