Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Proper way to create class with only one instance

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

like image 508
Richard J. Ross III Avatar asked Oct 12 '10 01:10

Richard J. Ross III


People also ask

How to create an instance of a class in Objective-C?

You can create an instance in Objective C in 3 different ways: Add the line #import "Product.h" in main.m file. By adding this line, it will detect the properties mentioned in the Product.h file. The keyword 'alloc' is used to allocate some memory to the instance of Product class.

What is an object in Objective C class?

Objective-C Classes & Objects. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and methods within a class are called members of the class.

How to create an object of an onlyone class?

The constructor is private, so you cannot create an object of OnlyOne class. There is a getInstance method which you have to call to return the instance. Note that it will be created only once. Edit: Spelling and grammar. Tagged correctly. Added question extension OP had posted as a solution. That's possible using a Singleton Class.

What is the difference between an object and a class?

Objects receive messages and objects are often referred as receivers. Objects contain instance variables. Objects and instance variables have scope. Classes hide an object's implementation. Properties are used to provide access to class instance variables in other classes.


1 Answers

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

like image 168
ennuikiller Avatar answered Nov 12 '22 18:11

ennuikiller