问题
I'm still confused a little with using Swift and was hoping that someone could help clarify when and why I would you them. From my understanding of Singleton's they are single class entities, meaning that if I have Class A and I create a shared instance of Class A in a Class B its just a reference to Class A in B, so if I change or modify the object that references Class A in Class B, the original object Class is is not effected, only the object in Class B is.
What if I wanted to have a Class A, and Class B, and in Class B create a direct reference to Class A, so any changes I make are effected in class A going forward. The class is directly modified not the instance of the object that references that class.
回答1:
Singleton
Look at this singleton class
final class Singleton {
static let sharedInstance = Singleton()
private init() { }
var value = 0
}
How does it work
There is NO WAY (outside of the source file where it is defined) to create more than 1 instance of this class because the initializer has been marked private
.
The only way to access an instance of Singleton is using sharedInstance
which does return the only instance available.
You can invoke sharedInstance
as many times as you want, from any class and then copy it as long as you want. Every variable will always contains a reference to the only instance of Singleton allocated on the Heap
.
So every change you do to sharedInstance
will be shared everywhere.
Example
let a = Singleton.sharedInstance
a.value = 1
let b = Singleton.sharedInstance
print(b.value) // 1
b.value = 2
print(a.value) // 2
来源:https://stackoverflow.com/questions/38793601/singleton-usage-in-swift