Skip to content

Instantly share code, notes, and snippets.

@oliverbarreto
Last active December 27, 2015 09:39
Show Gist options
  • Save oliverbarreto/7305640 to your computer and use it in GitHub Desktop.
Save oliverbarreto/7305640 to your computer and use it in GitHub Desktop.
Singleton Code for ObjectiveC iOS7
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
@manonthemoon42
Copy link

Very helpful ! Thank you !

Copy link

ghost commented Oct 13, 2014

Plain and simple, thanks a lot 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment