iOS: The singleton pattern
The Singleton Pattern is one of must used patterns in Objective-C.
If you are a Objective-C developer, of course you have seen the singleton pattern.
[UIApplication sharedApplication]
[NSBundle mainBundle]
[NSUserDefaults standardUserDefaults]
Do you know them?
they are class methods (they starts with "+"); they will return the (unique) shared instance of an object; they are singletons!
That's all!
Well, below is explained how to create a singleton for your custom class.
First sign your .h file with a class method +(id)sharedInstance;. It must return a object (id is ok!).
#import <Foundation/Foundation.h> @interface MyCustomClass : NSObject +(id)sharedInstance; @end
Second implement the +(id)sharedInstance method into the .m file. It will create the (shared) instance only one time and always return it.
+ (id)sharedInstance { static MyCustomClass *theSharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ theSharedInstance = [[self alloc] init]; }); return theSharedInstance; }
That's really all!
Don't forget: the singleton is also a whisky. We love singleton!













