Last active
December 27, 2015 09:39
-
-
Save oliverbarreto/7305640 to your computer and use it in GitHub Desktop.
Singleton Code for ObjectiveC iOS7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SingletonClass.h: | |
@interface SingletonClass : NSObject | |
@property (nonatomic, retain) NSString *myProperty; | |
+ (SingletonClass *)sharedInstance; | |
@end | |
SingletonClass.m: | |
@implentation | |
+ (SingletonClass *)sharedInstance | |
{ | |
// 1 | |
static SingletonClass *_sharedInstance = nil; | |
// 2 | |
static dispatch_once_t oncePredicate; | |
// 3 | |
dispatch_once(&oncePredicate, ^{ | |
_sharedInstance = [[SingletonClass alloc] init]; | |
}); | |
return _sharedInstance; | |
} | |
// There’s a lot going on in this short method: | |
// Declare a static variable to hold the instance of your class, ensuring it’s available globally inside your class. | |
// Declare the static variable dispatch_once_t which ensures that the initialization code executes only once. | |
// Use Grand Central Dispatch (GCD) to execute a block which initializes an instance of LibraryAPI. | |
// This is the essence of the Singleton design pattern: the initializer is never called again once the class has been instantiated. | |
- (id)init { | |
if (self = [super init]) { | |
myProperty = [[NSString alloc] initWithString:@"Default Value "]; | |
} | |
return self; | |
} | |
@end |
Very helpful ! Thank you !
Plain and simple, thanks a lot 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome thnx. Really helpful