0

In my app I have 3 view controllers, each of them working on the same collection of elements. Is there a way to share that collection other than passing it back and forth while performing segues? Can I somehow make collection accessible by all 3? What would be the right way to go about it?

Stormwaker
  • 381
  • 2
  • 12

2 Answers2

2

You could make a singleton containing the collection of elements. Singletons however are often considered bad as they can cause more problems than they solve, so perhaps using Core Data would be a better option.

class Singleton {

    static let shared = Singleton()

    private init(){}

    private let internalQueue = DispatchQueue(label: "com.singletoninternal.queue",
                                              qos: .default,
                                              attributes: .concurrent)

    private var _elementCollection: Set<T>

    var elementCollection: String {
        get {
            return internalQueue.sync {
               _elementCollection
            }
        }
        set (newState) {
            internalQueue.async(flags: .barrier) {
                self._elementCollection = newState
            }
        }
    }

    func setup(collection: Set<T>) {
        _elementCollection = collection
    }
}
Thijs van der Heijden
  • 1,147
  • 1
  • 10
  • 25
0

You can use singleton classes like below example

class YourClassName {
    static let shared = YourClassName()
    var test : String = "String"
    private init(){}
}

and then call your variables using

YourClassName.shared.test
koen
  • 5,383
  • 7
  • 50
  • 89