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
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.
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.
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.
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.
You need to do a little more than that. This describes how an objective-c singleton should be implemented: Objective-C Singleton
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With