With the Objective-C/Swift Singleton model, why do we create a shared instance and not just use class methods? [duplicate]

放肆的年华 提交于 2019-12-23 05:42:33

问题


It seems we always use a sharedInstance class variable to access the Singleton and perform methods on it. But why don't we just make all operations class methods and not have a variable to deal with at all? [SingletonClass uploadFile:(NSFile *)file] instead of [[SingletonClass sharedInstance] uploadFile:(NSFile *)file] (or the Swift equivalent).

What benefits do the variable bring? Or am I just overlooking some very integral concept in Singletons that not having a variable would prevent?

Furthermore, what stops this variable from being deallocated by memory? I know it's only created once, but why doesn't it ever get removed?


回答1:


You create a shared instance if you need to be able to store state. If you can get away with just class methods, that is definitely preferable. The less state you have in your app, especially with singletons, the fewer bugs you will create.



来源:https://stackoverflow.com/questions/24515662/with-the-objective-c-swift-singleton-model-why-do-we-create-a-shared-instance-a

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