photo from Apple |
Let's get started. Singleton is widely used in different object oriented programming languages. I love singleton, but my boss once said that he doesn't use this anymore and he feels he's a better programmer now because of that. I wonder why. Anyway, Singleton ensures a single instance of a class. It also provides global access point across your project. Pretty cool, right? That's why I love this. It is also widely used by Apple, however, the value of singleton in an application is still being debated by community.
I always use singleton, but don't be like me, I'm still a newbie in iOS Programming. I use singleton for passing data/object across my whole project, means globally. Ok, let's do some example. But wait again, my boss once told me to avoid applying singleton in AppDelegate class, it might make my app slow.
In your project, make a new file, a subclass of NSObject. Or you could just try this tutorial in your AppDelegate class, and change it in the future.
In your AppDelegate.h file, declare this inside your interface.
+ (AppDelegate *) getInstance;
we will be using that static getInstance later. Ok so for example, you need to have a BOOL in your project, and two or more classes need to access that BOOL (globally). That's when you need to have your singleton.
So declare a property, a bool, in yur AppDelegate.h. In my example, I'll use isPremium.
@property (nonatomic) BOOL isPremium;
Next, in your AppDelegate.m (implementation file), declare this static instance of your class, inside the implementation.
static AppDelegate *instance = nil;
Then implement the getInstance that we have declared a while ago in our header file.
+ (AppDelegate *) getInstance { if (instance == NULL) { // Thread safe allocation and initialization -> singletone object static dispatch_once_t pred; dispatch_once(&pred, ^{ instance = [[AppDelegate alloc] init]; }); } return instance; }So that's our Singleton, yey! Next, we will try to manipulate or toggle the values of our bool isPremium wherever I want.
SETTING THE VALUE
[AppDelegate getInstance].isPremium = YES;
GETTING THE VALUE
BOOL currentValue = [AppDelegate getInstance].isPremium;
So there you go. No need to worry that your data or object will be erased. Please subscribe if you liked this tutorial.
Post a Comment