The Singleton design pattern is one of the most frequently used design pattern when developing for the iOS platform. It is a very powerful way to share data across different parts of an iOS application without having to explicitly pass the data around manually.
The above code fragment defines a static variable called sharedMySingletonManager which is then initialized once and only once in sharedManager. The way that we ensure that it is only created once is by using the dispatch_once method from the Grand Central Dispatch (GCD). This is thread safe and handled entirely by the OS so you do not need to worry about it at all.
If you rather not use GCD, then you can the following code fragment for sharedManager:
Happy Singleton'ing! If you find this post useful, then mention me in the comments.
Overview
Singleton classes play an important role in iOS as they exhibit an extremely useful design pattern. Within the iOS SDK, the UIApplication class has a method called sharedApplication which when called from anywhere will return the UIApplication instance that is associated with the currently running application.How to implement the Singleton Class
You can implement the Singleton class in Objective-C as follows:
MyManager.h
@interface MySingletonManager : NSObject { NSString *someProperty; } @property (nonatomic, retain) NSString *someProperty; + (id)sharedManager; @end
MyManager.m
#import "MySingletonManager.h" @implementation MySingletonManager @synthesize someProperty; #pragma mark Singleton Methods +(id) sharedManager { static MySingletonManager *sharedMySingletonManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMySingletonManager = [[self alloc] init]; }); return sharedMySingletonManager; } - (id)init { if (self = [super init]) { someProperty = @"Default Property"; } return self; } - (void)dealloc { // should never be called, but included here for clarity } @end
The above code fragment defines a static variable called sharedMySingletonManager which is then initialized once and only once in sharedManager. The way that we ensure that it is only created once is by using the dispatch_once method from the Grand Central Dispatch (GCD). This is thread safe and handled entirely by the OS so you do not need to worry about it at all.
If you rather not use GCD, then you can the following code fragment for sharedManager:
Non-GCD Based
+ (id)sharedManager {
@synchronized(self) {
if (sharedMySingletonManager == nil)
sharedMySingletonManager = [[self alloc] init];
}
return sharedMySingletonManager;
}
Then, you can reference the Singleton from anywhere by calling the function below:Referencing the Singleton
MySingletonManager *sharedManager = [MySingletonManager sharedManager];
Happy Singleton'ing! If you find this post useful, then mention me in the comments.
View more documents from tasneemsayeed.