Objective-C Singleton
Want a shared instance of a class without putting everything in the application's delegate? Use a singleton class!
The following method returns a shared singleton instance of the class in question. Additional creation logic can be added, but make sure to place it inside the dispatch_once
block.
+ (__class__ *)sharedInstance {
static __class__ *_obj = nil;
static dispatch_once_t onceQueue;
dispatch_once(&onceQueue, ^{
_obj = [[__class__ alloc] init];
});
return _obj;
}
Replace __class__
with the actual class name.
Written by James Brooks
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Objective-c
Authors
Related Tags
#objective-c
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#