问题
I am trying out to create a singleton in SWIFT and this is what I have done so far
class Global {
class var sharedInstance:Global {
struct singleton {
static let instance:Global = Global()
}
return singleton.instance
}
}
var a = Global.sharedInstance
var b = Global()
if a === b {
println("Pointing to Same Instance")
}
else {
println("Pointing to different instance")
}
I have used computed type property to create a singleton (learnt that from another stackoverflow question).As of now the output is "Pointing to different instance".
What I am looking for is "a" and "b" in above example points to different instance of GLOBAL class and this breaks the point of singleton. How to make "a" and "b" in above example to point to the same instance of the class.
Thank you
回答1:
This pattern does not guarantee there will only ever be one instance of the Global
class. It just allows for anyone to access a single common instance of Global
via its sharedinstance
property.
So Global()
declares a new instance of the Global
class. But Global.sharedinstance
does not create a new instance of Global
, just fetches a pre-created one (that is created the first time anyone accesses it).
(If you alter your declaration of b
to read var b = Global.sharedinstance
you’ll see it confirms that a
and b
are pointing to the same instance.)
If you want to ban the creation of further instances of Global
, make its init
private:
private init() { }
But bear in mind you’ll still be able to create other Globals
from within the file in which it’s declared, so if you’re doing the above in a playground or single-file test project, you won’t see any effect.
回答2:
Class instance once in App life cycle.
class AccountManager {
static var sharedInstance = AccountManager()
var userInfo = (ID:"Arjun",Password:"123")
private init(){
print("allocate AccountManager")
}
}
here we set Private because :
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
also set static property of sharedInstance
because if you need to access class property without instance of class you must have to declare "Static".
来源:https://stackoverflow.com/questions/27769029/understanding-singleton-in-swift