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?
Asked
Active
Viewed 46 times
0
-
What about use core data? Or maybe use a parent viewcontorller and treat the others as child? – Alejandro L.Rocha Mar 12 '20 at 16:30
-
Are there a lot of elements or only a few? In the last case, you could maybe use `UserDefaults`. – koen Mar 12 '20 at 16:31
-
Well he had mention a collection, thats why I ignoer `UserDefailts` but yeah, could be another option – Alejandro L.Rocha Mar 12 '20 at 16:32
-
Make a super class for the view controllers with a static variable for the collection. – john elemans Mar 12 '20 at 16:34
-
How about Sigleton ? – Amit Mar 12 '20 at 16:38
-
Thank you all for your answers. I think I will go with Singleton for now. – Stormwaker Mar 12 '20 at 17:01
-
By the way, what's wrong with passing data from one view controller to the next? – koen Mar 12 '20 at 20:07
-
1Does this answer your question? [Pass data between view controllers constantly without a segue? USING SWIFT](https://stackoverflow.com/questions/29144857/pass-data-between-view-controllers-constantly-without-a-segue-using-swift) – Magnas Mar 12 '20 at 20:21
2 Answers
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
-
I'll look into Core Data and see if it's something I was looking for. – Stormwaker Mar 12 '20 at 16:48
-
It will be a lot more hassle to set it up, and if all you're passing around is a simple set or array, the solution I provided will be suffice. – Thijs van der Heijden Mar 12 '20 at 16:49
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