views:

55

answers:

3

I am trying to implement a class, that subclasses NSObject directly, that can only have one instance available throughout the entire time the application using it is running.

Currently I have this approach:

// MyClass.h

@interface MyClass : NSObject

+(MyClass *) instance;

@end

And the implementation:

// MyClass.m

// static instance of MyClass
static MyClass *s_instance;

@implementation MyClass

-(id) init
{
    [self dealloc];
    [NSException raise:@"No instances allowed of type MyClass" format:@"Cannot create instance of MyClass. Use the static instance method instead."];

    return nil;
}

-(id) initInstance
{
    return [super init];
}

+(MyClass *) instance {
    if (s_instance == nil)
    {
        s_instance = [[DefaultLiteralComparator alloc] initInstance];
    }

    return s_instance;    
}

@end

Is this the proper way to accomplish such a task?

Thanks

+4  A: 

You need to do a little more than that. This describes how an objective-c singleton should be implemented: Objective-C Singleton

ennuikiller
Thank you, I will use this solution!
Richard J. Ross III
Also see http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like
sdolan
Nice link, helped me a lot!
Richard J. Ross III
A: 

In your scenario, there is still a way to create a second instance of your class:

MyClass *secondInstance = [[MyClass alloc] initInstance]; //we have another instance!

What you want is to override your class's +(id)alloc method:

+(id)alloc{
    @synchronized(self){
        NSAssert(s_instance == nil, @"Attempted to allocate a second instance of singleton(MyClass)");
        s_instance = [super alloc];
        return s_instance;
    }
    return nil;
}
executor21
Yes, but the `initInstance` method is not in the header, only in the implementation...
Richard J. Ross III
You'll get a compiler warning, but that's it. It will still run, and create a second instance. Also, nothing prohibits a method of a class from creating another instance of itself.
executor21
@executor21: Actually, you won't get a compiler warning, because the definition of initInstance comes before its only use.
JeremyP
+1  A: 

Here you'll find a xcode template to generate the skeleton of a singleton class that inherits from NSObject.

Beware of the warning
I altered the plist by hand.

vikingosegundo