Using the Swift Singleton

余生颓废 提交于 2019-12-11 01:58:54

问题


I've got the following Singleton class:

class Singleton {
    static let sharedInstance = Singleton()
}

I can find very little online about how to use the numerous swift implementations of the Singleton pattern. I have used it before in Objective-C on a previous application but to me it seemed much more straight forward.

For instance, if I wanted to create an array of custom objects that could be used anywhere in the application, how would I declare it, and how would I implement it. In my objective-C Singleton class, I create global variables in the class file, and then implement it like so:

singletonClass *mySingleton = [singletonClass sharedsingletonClass];
mySingleton.whatever = "blaaaah"

I appreciate the help! Also I'm new around here and new to Swift.


回答1:


There is a lot of info available on singletons in Swift. Have you come across this article with your Google prowess? http://krakendev.io/blog/the-right-way-to-write-a-singleton

But to answer your question, you can simply define anything you'd like to use normally.

class Singleton {
    static let sharedInstance = Singleton() // this makes singletons easy in Swift
    var stringArray = [String]()

}

let sharedSingleton = Singleton.sharedInstance

sharedSingleton.stringArray.append("blaaaah") // ["blaaaah"]

let anotherReferenceToSharedSingleton = Singleton.sharedInstance

print(anotherReferenceToSharedSingleton.stringArray) // "["blaaaah"]\n"



回答2:


Agree with Andrew Sowers. Just remember that you must also declare a private initializer like this:

class Singleton: NSObject {
    static let sharedInstance = Singleton()
    private override init() {}
}

Without this private init(), other objects could create their own instance:

let mySingleton = Singleton()

Now there are two instances, Singleton.sharedInstance and mySingleton - no longer a singleton! I discovered this via a nasty bug where multiple "singletons" were firing timers and wreaking havoc.



来源:https://stackoverflow.com/questions/34865278/using-the-swift-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!