Skip to content

Instantly share code, notes, and snippets.

@pjrobertson
Created February 28, 2014 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjrobertson/9273839 to your computer and use it in GitHub Desktop.
Save pjrobertson/9273839 to your computer and use it in GitHub Desktop.
Shows how to properly make singletons/sharedInstances in objective-C, using a dispatch_once_t token
// MyObject.h
@interface MyObject : NSObject
+ (instancetype)sharedInstance;
@end
// MyObject.m
@implementation MyObject
+ (instancetype)sharedInstance {
static dispatch_once_t once;
static MyObject *sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment