开发者

What is meant by singleton object?and what is it usage?

开发者 https://www.devze.com 2023-04-08 21:20 出处:网络
Can anyone explain to me what a singleton object is? In many tutorials I found something like \"create a sigleton object\". Now I am working in iphone game development using cocos2d. I read \"Create a

Can anyone explain to me what a singleton object is? In many tutorials I found something like "create a sigleton object". Now I am working in iphone game development using cocos2d. I read "Create a singleton object to keep all the Game Center code in one spot" in raywenderlich multiplayer tutorial, and also he says:

+ (GCHelper *)sharedInstance;

This static method to retrive the singleton instance of this class. But I d开发者_JAVA技巧on't know what a singleton is, or how to use it.


A Singleton object is an object for which there is only a single instance for a given class. The Singleton pattern is used when you want to guarantee that a single instance of a class will be shared across clients in a system.

Check out the C2 wiki page for more information.

Here are some posts with examples of the use of singletons in objective-c:

  • Using the Singleton Pattern in Objective-C
  • Singletons: You're doing them wrong


A singleton is an instance of a class that is meant to be the only one of its kind. You usually have a class method that returns a pointer to this single instance or creates it if it didnot exist yet.

Some examples of singletons are: NSFileManager defaultManager NSUserDefaults standardUserdefaults NSCharacterSet whitespaceCharacterset

Singletons are the generally accepted method to hold model data and code in a central place that you can access from everwhere in your other code. All you need to do is to add the header and get the singleton pointer via class method.

See here for a comparison of singleton versus global variables: http://www.cocoanetics.com/2009/05/the-death-of-global-variables/


Singleton object means there is only one object throughout your application. If you used any properties in a singleton class and you access this property using object of this class, which is also called singleton object, you will get the same value in you whole application until you change it manually. This concept is generally used to maintain some fix values that your application required like if your application has login process than may be you required logged in username to be carried in your application for use at any point of application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号