Wayne Filkins Wayne Filkins - 14 days ago 9
Swift Question

How to use an array over multiple view controllers?

I have been playing around with a lot of stuff involving arrays and scrollviews. I have mostly stayed within the confines of view controllers, so usually i'll grab data from firebase, add it to an array, and then send it to the tableview or collectionview. What I'm trying to do now is actually navigate between viewcontrollers (or multiple copies of the same view controller) and applying the array items to each view controller.

For example I want to be able to grab some photos from firebase, put them in an array of url strings or whatever. Then I want to put a photo on the background of a view controller. Then when I push the over button it goes navigates to the next view controller and puts the next photo as the background there, etc.

I understand there are probably multiple ways to do this and I was wondering what is the most efficient way? Do I just put an array in a Global class and access that from all the view controllers? Or do I just keep the array in the first view controller, then as I navigate, keep sending it to the next view controller over and over? Also there will be a LOT of items and objects and arrays here so that's why I'm looking for efficiency. Thanks in advance to anyone able to help with this, and I hope I explained it well enough!

Answer

This is a very simple way of adding and retrieving String value from a struct, here you are saving the image url string as a value in a dictionary and it's key is going to be the ViewController name.

struct SavedData {
    static private var imagesDictionary: [String: String] = [:]

    static func image(for viewController: UIViewController) -> String? {
        return imagesDictionary["\(type(of: viewController))"]
    }

    static func add(image name: String, for viewController: UIViewController) {
        self.imagesDictionary["\(type(of: viewController))"] = name
    }
}

saving a value is very simple, if you're saving the data in a viewController and you want a specific image to be saved for that viewController you can use self

SavedData.add(image: "img1.png", for: self)

And if you want to save an image for a different viewController, do it like this.

SavedData.add(image: "img2.png", for: SecondViewController())

Retrieving the image is also very simple, you should call this method in the viewController that you want to assign the image to.

let savedImage = SavedData.image(for: self)
print(savedImage!)