Singleton in Interface Builder with ARC - objective-c

My question is quite similar to this one: Use Singleton In Interface Builder?
The only difference is that I use ARC. So, if simplified, my singleton looks like that:
Manager.m
#implementation Manager
+ (instancetype)sharedManager {
__strong static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
#end
So the question is if it's possible to adopt it for Interface Builder still being with ARC?
Of course, I understand that it might be simpler just to rewrite that class without ARC so the question is rather academic. :)

When the nib is unarchived, it'll attempt to either alloc/init or alloc/initWithCoder: a new instance of the class.
So, what you could do is intercept that call and re-route it to return your singleton:
+ (id)sharedInstance {
static Singleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self actualAlloc] actualInit];
});
return sharedInstance;
}
+ (id)actualAlloc {
return [super alloc];
}
+ (id)alloc {
return [Singleton sharedInstance];
}
- (id)actualInit {
self = [super init];
if (self) {
// singleton setup...
}
return self;
}
- (id)init {
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
return self;
}
This allows -init and -initWithCoder: to be safely called multiple times on the same object. It's generally not recommended to allow this, but given that singletons are already cases of "a place where things can get really wonky", this isn't the worst you could do.

Just to be complete, here's an implementation of Singleton which might be used from Interface Builder. The difference is in actualAlloc method. As [super alloc] would still call [self allocWithZone:] – it wouldn't allocate the object.
Singleton.h
#interface Singleton : NSObject
+ (instancetype)sharedInstance;
#end
Singleton.m
#implementation Singleton
+ (instancetype)sharedInstance {
__strong static id _sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self _alloc] _init];
});
return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
+ (id)alloc {
return [self sharedInstance];
}
- (id)init {
return self;
}
+ (id)_alloc {
return [super allocWithZone:NULL]; //this is important, because otherwise the object wouldn't be allocated
}
- (id)_init {
return [super init];
}
#end

#Eugene, from iOS doc set, "For historical reasons, alloc invokes allocWithZone:.", so, there is no need to reimplement the alloc method.

Related

How do you create a global instance of a class in Objective-C

I am very new to Objective C and stumbled upon this problem.
How is it possible to create a global instance of a class in Objective C which is accessible from multiple classes and the main function?
You can do it in this way:
+(MyClass *) sharedInstance
{
static id sharedInstance = nil;
#synchronized(self)
{
if (!sharedInstance)
{
sharedInstance = [[MyClass alloc] init];
}
return sharedInstance;
}
}
Just access the object by this single line of code:
[MyClass sharedInstance]
Hope it helps!! Happy Coding :)
Add a method to your class that returns this specific instance.
The most common case is the singleton. You can also look up "shared instance".
You can use singleton, import the .h file in your .pch file, by doing that every file will have this imported :
YourClass.h :
#interface YourClass : NSObject
/**
* Method to get the singleton instance
* #return Instance of YourClass
*/
+ (YourClass *)instance;
#end
YourClass.m :
#import "YourClass.h"
#interface YourClass(){
}
#end
#pragma mark -
#implementation YourClass
- (id)init{
//prevents normal inits
return nil;
}
+ (YourClass *)instance
{
static YourClass *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] initSingelton];
});
return instance;
}
- (id)initSingelton{
if (self = [super init]) {
//do stuff here
return self;
}
return nil;
}

Upgrade an existing singleton to ARC

In Objective-C, how to write a singleton with ARC? In ARC, it is not allowed to overwrite the release, autorelease, retain, retainCount methods, how to avoid a object to be released? I know without ARC, a classic singleton would like below:
#interface SingletonObject
+ (SingletonObject*)sharedObject;
#end
SingletonObject *sharedObj;
#implementation SingletonObject
+ (id)allocWithZone:(NSZone *)zone
{
if (sharedObj == nil) {
//So the code [[SingletonObject alloc] init] is equal with [SingletonObject sharedObject]
sharedObj = [super allocWithZone:zone];
}
return sharedObj;
}
+ (void)initialize
{
if (self == [SingletonObject class]) {
sharedObj = [[SingletonObject alloc] init];
}
}
+ (SingletonObject*)sharedObject
{
return sharedObj;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
- (id)init {
self = [super init];
if (self) {
//...
}
return self;
}
#end
Is it safe to just remove the retain, retainCount, release, autorelease methods? Thanks!
You only need one method to implement a class that supports the singleton pattern:
+ (instancetype)sharedInstance
{
static id _sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
Copy/paste that into any class and it'll have a shared instance. Any code beyond that is just added complexity that really isn't necessary. I'll sometimes add:
- (void)dealloc
{
*(char*)0x42 = 'b';
// no super, ARC all the way
}
That'll cause a very specific crash if my shared instance is ever deallocated due to a bug. (Yes, hex 0x42 is not 42, but it leaves a nice 0x000000042 in a register in the crash log, making it immediately identifiable what happened.)
Yes.
-sharedObject should be +sharedObject, though (class method). Just make sure you always use that.

Singleton with ARC

My question is the following: I have a singleton type object (I'm using ARC) that has this code in the implementation file
+(id)sharedInstance
{
static DataManager *sharedInstance;
if (sharedInstance == nil) {
sharedInstance = [[DataManager alloc] init];
}
return sharedInstance;
}
+(NSManagedObjectContext *)getManagedContext
{
AppDelegate *applicationDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
return [applicationDelegate managedObjectContext];
}
+(void)saveContext:(NSManagedObjectContext *)context
{
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
#pragma mark - Data management methods
+(void)addPersonWithName:(NSString *)name andPicture:(UIImage *)picture
{
NSManagedObjectContext *context = [self getManagedContext]; //no problem here
//some code
[self saveContex:context]; // no known class method for selector saveContext:
}
Why is that? The method is declared in the .h file with + ... the getManagedContext model doesn't give this error????
The keyword self inside a method references the owner of the method, which is the instance of the object for instance methods, and the class for class methods. However, the message saveContex is missing a t at the end (saveContext).
dispatch_once singleton
And here is a better singleton idiom compatible with ARC:
+(MySingleton *)sharedInstance {
static dispatch_once_t pred;
static MySingleton *shared = nil;
dispatch_once(&pred, ^{
shared = [[MySingleton alloc] init];
});
return shared;
}
Same code as Xcode template
Same code as a Xcode template with placeholders:
+ (<#class#> *)shared<#name#> {
static dispatch_once_t onceToken;
static <#class#> *shared<#name#> = nil;
dispatch_once(&onceToken, ^{
shared<#name#> = <#initializer#>;
});
return shared<#name#>;
}
Same code + disabled alloc/init/new
Want to clue users that they should call sharedInstance instead alloc/init/new? You can disable methods with attribute unavailable. This will cause a compiler error if any of those methods is called on the class.
#import <Foundation/Foundation.h>
#interface MySingleton : NSObject
+(instancetype) sharedInstance;
// clue for improper use (produces compile time error)
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));
#end
#import "MySingleton.h"
#implementation MySingleton
+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
-(instancetype) initUniqueInstance {
return [super init];
}
#end
Warning: dispatch_once is not reentrant
Don't make a recursive call to sharedInstance from inside the dispatch_once block.
If you call dispatch_once from several threads it will act as a barrier preventing concurrent access. But if you call it again in the same thread from inside the block it will deadlock the thread. This example illustrates the problem:
#import <Foundation/Foundation.h>
static NSRecursiveLock *_lock = nil;
// constructor = run before main. used = emit code even if the function is not referenced.
// See http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
static void runBeforeMain(void) __attribute__ ((constructor, used));
static void runBeforeMain(void) {
_lock = [NSRecursiveLock new];
}
static void test(void)
{
static NSUInteger count = 0;
NSLog(#"iteration #%lu", ++count);
// WRONG: deadlock!
//static dispatch_once_t token;
//dispatch_once(&token, ^{
// test();
//});
// OK
[_lock lock];
test();
[_lock unlock];
--count;
}
int main(int argc, char **argv) {
#autoreleasepool {
test();
}
return EXIT_SUCCESS;
}
+initialize singleton
Using +initialize is an alternative idiom to create a singleton. Pros: It is several times faster than dispatch_once. Cons: +initialize is called once per class, so if you subclass the singleton, an instance will be created for each parent class too. Use it only if you know the singleton will not be subclassed.
static id sharedInstance;
+ (void) initialize {
// subclassing would result in an instance per class, probably not what we want
NSAssert([MySingleton class] == self, #"Subclassing is not welcome");
sharedInstance = [[super alloc] initUniqueInstance];
}
+(instancetype) sharedInstance {
return sharedInstance;
}

Singleton pattern in objc, how to keep init private?

How can i make sure user do not call init, instead client should call sharedSingleton to get a shared instance.
#synthesize delegate;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
+ (LoginController *)sharedSingleton
{
static LoginController *sharedSingleton;
#synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[LoginController alloc] init];
CdtMiscRegisterConnectionChangeListenerObjc(test_ConnectionChangeListenerCallback);
return sharedSingleton;
}
}
I've seen it done two ways.
Throw an exception inside init.
Have the object returned by init be your singleton object.
Just to be clear, though, don't do this. It's unnecessary and will make your singletons overly difficult to test and subclass.
edit to add examples
Throw an exception in init
- (instancetype)init {
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (instancetype)initPrivate {
self = [super init];
if (self) {
}
return self;
}
+ (instancetype)sharedInstance {
static MySingleton *sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] initPrivate];
});
return sharedInstance;
}
Have init return your singleton
- (instancetype)init {
return [[self class] sharedInstance];
}
- (instancetype)initPrivate {
self = [super init];
if (self) {
}
return self;
}
+ (instancetype)sharedInstance {
static MySingleton2 *sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] initPrivate];
});
return sharedInstance;
}
Use UNAVAILABLE_ATTRIBUTE abolish init method, and implement initPrivate
+ (instancetype)shareInstance;
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;
implement
+ (instancetype)shareInstance {
static MyClass *shareInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [[super allocWithZone:NULL] initPrivate];
});
return shareInstance;
}
- (instancetype)initPrivate {
self = [super init];
if (self) {
}
return self;
}
// MARK: Rewrite
+ (id)allocWithZone:(struct _NSZone *)zone {
return [MyClass shareInstance];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
Short answer: you can't; Objective-C has no concept of private methods.
Check out the answer to this similar question.
You can't make methods private in Objective-C. You could raise a NSException if the wrong initializer is invoked.
- (id)init
{
[NSException exceptionWithName:#"InvalidOperation" reason:#"Cannot invoke init." userInfo:nil];
}

What should my Objective-C singleton look like? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
My singleton accessor method is usually some variant of:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
#synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
What could I be doing to improve this?
Another option is to use the +(void)initialize method. From the documentation:
The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
So you could do something akin to this:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}
#interface MySingleton : NSObject
{
}
+ (MySingleton *)sharedSingleton;
#end
#implementation MySingleton
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
#synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
#end
[Source]
Per my other answer below, I think you should be doing:
+ (id)sharedFoo
{
static dispatch_once_t once;
static MyFoo *sharedFoo;
dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; });
return sharedFoo;
}
Since Kendall posted a threadsafe singleton that attempts to avoid locking costs, I thought I would toss one up as well:
#import <libkern/OSAtomic.h>
static void * volatile sharedInstance = nil;
+ (className *) sharedInstance {
while (!sharedInstance) {
className *temp = [[self alloc] init];
if(!OSAtomicCompareAndSwapPtrBarrier(0x0, temp, &sharedInstance)) {
[temp release];
}
}
return sharedInstance;
}
Okay, let me explain how this works:
Fast case: In normal execution sharedInstance has already been set, so the while loop is never executed and the function returns after simply testing for the variable's existence;
Slow case: If sharedInstance doesn't exist, then an instance is allocated and copied into it using a Compare And Swap ('CAS');
Contended case: If two threads both attempt to call sharedInstance at the same time AND sharedInstance doesn't exist at the same time then they will both initialize new instances of the singleton and attempt to CAS it into position. Whichever one wins the CAS returns immediately, whichever one loses releases the instance it just allocated and returns the (now set) sharedInstance. The single OSAtomicCompareAndSwapPtrBarrier acts as both a write barrier for the setting thread and a read barrier from the testing thread.
static MyClass *sharedInst = nil;
+ (id)sharedInstance
{
#synchronize( self ) {
if ( sharedInst == nil ) {
/* sharedInst set up in init */
[[self alloc] init];
}
}
return sharedInst;
}
- (id)init
{
if ( sharedInst != nil ) {
[NSException raise:NSInternalInconsistencyException
format:#"[%# %#] cannot be called; use +[%# %#] instead"],
NSStringFromClass([self class]), NSStringFromSelector(_cmd),
NSStringFromClass([self class]),
NSStringFromSelector(#selector(sharedInstance)"];
} else if ( self = [super init] ) {
sharedInst = self;
/* Whatever class specific here */
}
return sharedInst;
}
/* These probably do nothing in
a GC app. Keeps singleton
as an actual singleton in a
non CG app
*/
- (NSUInteger)retainCount
{
return NSUIntegerMax;
}
- (oneway void)release
{
}
- (id)retain
{
return sharedInst;
}
- (id)autorelease
{
return sharedInst;
}
Edit: This implementation obsoleted with ARC. Please have a look at How do I implement an Objective-C singleton that is compatible with ARC? for correct implementation.
All the implementations of initialize I've read in other answers share a common error.
+ (void) initialize {
_instance = [[MySingletonClass alloc] init] // <----- Wrong!
}
+ (void) initialize {
if (self == [MySingletonClass class]){ // <----- Correct!
_instance = [[MySingletonClass alloc] init]
}
}
The Apple documentation recommend you check the class type in your initialize block. Because subclasses call the initialize by default. There exists a non-obvious case where subclasses may be created indirectly through KVO. For if you add the following line in another class:
[[MySingletonClass getInstance] addObserver:self forKeyPath:#"foo" options:0 context:nil]
Objective-C will implicitly create a subclass of MySingletonClass resulting in a second triggering of +initialize.
You may think that you should implicitly check for duplicate initialization in your init block as such:
- (id) init { <----- Wrong!
if (_instance != nil) {
// Some hack
}
else {
// Do stuff
}
return self;
}
But you will shoot yourself in the foot; or worse give another developer the opportunity to shoot themselves in the foot.
- (id) init { <----- Correct!
NSAssert(_instance == nil, #"Duplication initialization of singleton");
self = [super init];
if (self){
// Do stuff
}
return self;
}
TL;DR, here's my implementation
#implementation MySingletonClass
static MySingletonClass * _instance;
+ (void) initialize {
if (self == [MySingletonClass class]){
_instance = [[MySingletonClass alloc] init];
}
}
- (id) init {
ZAssert (_instance == nil, #"Duplication initialization of singleton");
self = [super init];
if (self) {
// Initialization
}
return self;
}
+ (id) getInstance {
return _instance;
}
#end
(Replace ZAssert with our own assertion macro; or just NSAssert.)
A thorough explanation of the Singleton macro code is on the blog Cocoa With Love
http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html.
I have an interesting variation on sharedInstance that is thread safe, but does not lock after the initialization. I am not yet sure enough of it to modify the top answer as requested, but I present it for further discussion:
// Volatile to make sure we are not foiled by CPU caches
static volatile ALBackendRequestManager *sharedInstance;
// There's no need to call this directly, as method swizzling in sharedInstance
// means this will get called after the singleton is initialized.
+ (MySingleton *)simpleSharedInstance
{
return (MySingleton *)sharedInstance;
}
+ (MySingleton*)sharedInstance
{
#synchronized(self)
{
if (sharedInstance == nil)
{
sharedInstance = [[MySingleton alloc] init];
// Replace expensive thread-safe method
// with the simpler one that just returns the allocated instance.
SEL origSel = #selector(sharedInstance);
SEL newSel = #selector(simpleSharedInstance);
Method origMethod = class_getClassMethod(self, origSel);
Method newMethod = class_getClassMethod(self, newSel);
method_exchangeImplementations(origMethod, newMethod);
}
}
return (MySingleton *)sharedInstance;
}
Short answer: Fabulous.
Long answer: Something like....
static SomeSingleton *instance = NULL;
#implementation SomeSingleton
+ (id) instance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (instance == NULL){
instance = [[super allocWithZone:NULL] init];
}
});
return instance;
}
+ (id) allocWithZone:(NSZone *)paramZone {
return [[self instance] retain];
}
- (id) copyWithZone:(NSZone *)paramZone {
return self;
}
- (id) autorelease {
return self;
}
- (NSUInteger) retainCount {
return NSUIntegerMax;
}
- (id) retain {
return self;
}
#end
Be sure to read the dispatch/once.h header to understand what's going on. In this case the header comments are more applicable than the docs or man page.
I've rolled singleton into a class, so other classes can inherit singleton properties.
Singleton.h :
static id sharedInstance = nil;
#define DEFINE_SHARED_INSTANCE + (id) sharedInstance { return [self sharedInstance:&sharedInstance]; } \
+ (id) allocWithZone:(NSZone *)zone { return [self allocWithZone:zone forInstance:&sharedInstance]; }
#interface Singleton : NSObject {
}
+ (id) sharedInstance;
+ (id) sharedInstance:(id*)inst;
+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst;
#end
Singleton.m :
#import "Singleton.h"
#implementation Singleton
+ (id) sharedInstance {
return [self sharedInstance:&sharedInstance];
}
+ (id) sharedInstance:(id*)inst {
#synchronized(self)
{
if (*inst == nil)
*inst = [[self alloc] init];
}
return *inst;
}
+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst {
#synchronized(self) {
if (*inst == nil) {
*inst = [super allocWithZone:zone];
return *inst; // assignment and return on first allocation
}
}
return nil; // on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
//do nothing
}
- (id)autorelease {
return self;
}
#end
And here is an example of some class, that you want to become singleton.
#import "Singleton.h"
#interface SomeClass : Singleton {
}
#end
#implementation SomeClass
DEFINE_SHARED_INSTANCE;
#end
The only limitation about Singleton class, is that it is NSObject subclass. But most time I use singletons in my code they are in fact NSObject subclasses, so this class really ease my life and make code cleaner.
This works in a non-garbage collected environment also.
#interface MySingleton : NSObject {
}
+(MySingleton *)sharedManager;
#end
#implementation MySingleton
static MySingleton *sharedMySingleton = nil;
+(MySingleton*)sharedManager {
#synchronized(self) {
if (sharedMySingleton == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedMySingleton;
}
+(id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if (sharedMySingleton == nil) {
sharedMySingleton = [super allocWithZone:zone];
return sharedMySingleton; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
-(void)dealloc {
[super dealloc];
}
-(id)copyWithZone:(NSZone *)zone {
return self;
}
-(id)retain {
return self;
}
-(unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be release
}
-(void)release {
//do nothing
}
-(id)autorelease {
return self;
}
-(id)init {
self = [super init];
sharedMySingleton = self;
//initialize here
return self;
}
#end
Shouln't this be threadsafe and avoid the expensive locking after the first call?
+ (MySingleton*)sharedInstance
{
if (sharedInstance == nil) {
#synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[MySingleton alloc] init];
}
}
}
return (MySingleton *)sharedInstance;
}
Here's a macro that I put together:
http://github.com/cjhanson/Objective-C-Optimized-Singleton
It is based on the work here by Matt Gallagher
But changing the implementation to use method swizzling as described here by Dave MacLachlan of Google.
I welcome comments / contributions.
How about
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
if (gInstance == NULL) {
#synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
}
return(gInstance);
}
So you avoid the synchronization cost after initialization?
For an in-depth discussion of the singleton pattern in Objective-C, look here:
Using the Singleton Pattern in Objective-C
KLSingleton is:
Subclassible (to the n-th degree)
ARC compatible
Safe with alloc and init
Loaded lazily
Thread-safe
Lock-free (uses +initialize, not #synchronize)
Macro-free
Swizzle-free
Simple
KLSingleton
You don't want to synchronize on self... Since the self object doesn't exist yet! You end up locking on a temporary id value. You want to ensure that no one else can run class methods ( sharedInstance, alloc, allocWithZone:, etc ), so you need to synchronize on the class object instead:
#implementation MYSingleton
static MYSingleton * sharedInstance = nil;
+( id )sharedInstance {
#synchronized( [ MYSingleton class ] ) {
if( sharedInstance == nil )
sharedInstance = [ [ MYSingleton alloc ] init ];
}
return sharedInstance;
}
+( id )allocWithZone:( NSZone * )zone {
#synchronized( [ MYSingleton class ] ) {
if( sharedInstance == nil )
sharedInstance = [ super allocWithZone:zone ];
}
return sharedInstance;
}
-( id )init {
#synchronized( [ MYSingleton class ] ) {
self = [ super init ];
if( self != nil ) {
// Insert initialization code here
}
return self;
}
}
#end
Just wanted to leave this here so I don't lose it. The advantage to this one is that it's usable in InterfaceBuilder, which is a HUGE advantage. This is taken from another question that I asked:
static Server *instance;
+ (Server *)instance { return instance; }
+ (id)hiddenAlloc
{
return [super alloc];
}
+ (id)alloc
{
return [[self instance] retain];
}
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
instance = [[Server hiddenAlloc] init];
}
}
- (id) init
{
if (instance)
return self;
self = [super init];
if (self != nil) {
// whatever
}
return self;
}
static mySingleton *obj=nil;
#implementation mySingleton
-(id) init {
if(obj != nil){
[self release];
return obj;
} else if(self = [super init]) {
obj = self;
}
return obj;
}
+(mySingleton*) getSharedInstance {
#synchronized(self){
if(obj == nil) {
obj = [[mySingleton alloc] init];
}
}
return obj;
}
- (id)retain {
return self;
}
- (id)copy {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
if(obj != self){
[super release];
}
//do nothing
}
- (id)autorelease {
return self;
}
-(void) dealloc {
[super dealloc];
}
#end
I know there are a lot of comments on this "question", but I don't see many people suggesting using a macro to define the singleton. It's such a common pattern and a macro greatly simplifies the singleton.
Here are the macros I wrote based on several Objc implementations I've seen.
Singeton.h
/**
#abstract Helps define the interface of a singleton.
#param TYPE The type of this singleton.
#param NAME The name of the singleton accessor. Must match the name used in the implementation.
#discussion
Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
*/
#define SingletonInterface(TYPE, NAME) \
+ (TYPE *)NAME;
/**
#abstract Helps define the implementation of a singleton.
#param TYPE The type of this singleton.
#param NAME The name of the singleton accessor. Must match the name used in the interface.
#discussion
Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
*/
#define SingletonImplementation(TYPE, NAME) \
static TYPE *__ ## NAME; \
\
\
+ (void)initialize \
{ \
static BOOL initialized = NO; \
if(!initialized) \
{ \
initialized = YES; \
__ ## NAME = [[TYPE alloc] init]; \
} \
} \
\
\
+ (TYPE *)NAME \
{ \
return __ ## NAME; \
}
Example of use:
MyManager.h
#interface MyManager
SingletonInterface(MyManager, sharedManager);
// ...
#end
MyManager.m
#implementation MyManager
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
SingletonImplementation(MyManager, sharedManager);
// ...
#end
Why a interface macro when it's nearly empty? Code consistency between the header and code files; maintainability in case you want to add more automatic methods or change it around.
I'm using the initialize method to create the singleton as is used in the most popular answer here (at time of writing).
With Objective C class methods, we can just avoid using the singleton pattern the usual way, from:
[[Librarian sharedInstance] openLibrary]
to:
[Librarian openLibrary]
by wrapping the class inside another class that just has Class Methods, that way there is no chance of accidentally creating duplicate instances, as we're not creating any instance!
I wrote a more detailed blog here :)
To extend the example from #robbie-hanson ...
static MySingleton* sharedSingleton = nil;
+ (void)initialize {
static BOOL initialized = NO;
if (!initialized) {
initialized = YES;
sharedSingleton = [[self alloc] init];
}
}
- (id)init {
self = [super init];
if (self) {
// Member initialization here.
}
return self;
}
My way is simple like this:
static id instanceOfXXX = nil;
+ (id) sharedXXX
{
static volatile BOOL initialized = NO;
if (!initialized)
{
#synchronized([XXX class])
{
if (!initialized)
{
instanceOfXXX = [[XXX alloc] init];
initialized = YES;
}
}
}
return instanceOfXXX;
}
If the singleton is initialized already, the LOCK block will not be entered. The second check if(!initialized) is to make sure it is not initialized yet when the current thread acquires the LOCK.
I've not read through all the solutions, so forgive if this code is redundant.
This is the most thread safe implementation in my opinion.
+(SingletonObject *) sharedManager
{
static SingletonObject * sharedResourcesObj = nil;
#synchronized(self)
{
if (!sharedResourcesObj)
{
sharedResourcesObj = [[SingletonObject alloc] init];
}
}
return sharedResourcesObj;
}
I usually use code roughly similar to that in Ben Hoffstein's answer (which I also got out of Wikipedia). I use it for the reasons stated by Chris Hanson in his comment.
However, sometimes I have a need to place a singleton into a NIB, and in that case I use the following:
#implementation Singleton
static Singleton *singleton = nil;
- (id)init {
static BOOL initialized = NO;
if (!initialized) {
self = [super init];
singleton = self;
initialized = YES;
}
return self;
}
+ (id)allocWithZone:(NSZone*)zone {
#synchronized (self) {
if (!singleton)
singleton = [super allocWithZone:zone];
}
return singleton;
}
+ (Singleton*)sharedSingleton {
if (!singleton)
[[Singleton alloc] init];
return singleton;
}
#end
I leave the implementation of -retain (etc.) to the reader, although the above code is all you need in a garbage collected environment.
The accepted answer, although it compiles, is incorrect.
+ (MySingleton*)sharedInstance
{
#synchronized(self) <-------- self does not exist at class scope
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}
Per Apple documentation:
... You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self.
Even if using self works, it shouldn't and this looks like a copy and paste mistake to me.
The correct implementation for a class factory method would be:
+ (MySingleton*)getInstance
{
#synchronized([MySingleton class])
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}