Creating your own Singletons in Objective-C
No Comments
Singletons can be considered like a global class instance that can be accessed by any other class in the program. This is particularly useful if you have certain states or methods that can be grouped up into a single class and allowing other classes to make necessary calls to it. This practice is quite widely used by Apple in their frameworks such as [UIApplication sharedApplication] and [NSNotificationCenter defaultCenter] etc.
We start by creating a new class subclassing NSObject (or other classes that you want) and add a class function to access this singleton.
In the .h,
@interface APIClient : NSObject + (APIClient *)sharedInstance; @end
After that, we implement the method to access the singleton in .m,
#import "APIClient.h"
@implementation APIClient
+ (id)sharedInstance {
static APIClient *__sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedInstance = [[APIClient alloc] init]:
});
return __sharedInstance;
}
//...
@end
That’s it! Now all you have to do is to do a #import “APIClient.h” in other classes that you want to use it.
And called the class method [APIClient sharedInstance] to get the single instance throughout your application!
