6

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

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201

2 Answers2

6

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

ennuikiller
  • 46,381
  • 14
  • 112
  • 137
0

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
  • 4,532
  • 6
  • 28
  • 38
  • Yes, but the `initInstance` method is not in the header, only in the implementation... – Richard J. Ross III Oct 12 '10 at 01:17
  • 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 Oct 12 '10 at 01:21
  • Actually, you won't get a compiler warning, because the definition of initInstance comes before its only use. – JeremyP Oct 12 '10 at 09:45