[Objective-C] Singletons
Some days ago i'm read at @CocoaSamurai blog a post intitled "Singletons: You're doing them wrong"
Ok, but what is Singleton and for whats is needed?
A singleton class returns the same instance no matter how many times an application requests it. A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource. DevPedia-CocoaCoreCode sample MyClass.h
#import
@interface MyClass : NSObject {
}
+(MyClass*)sharedInstance;
-(void)sharedMethod;
@end
MyClass.m
@implementation MyClass
static MyClass* _sharedInstance = nil;
+(MyClass*)sharedInstance
{
@synchronized([MyClass class])
{
if (!_sharedInstance)
[[self alloc] init];
return _sharedInstance;
}
return nil;
}
-(void)sharedMethod {
NSLog(@"Hello i'm a singleton class");
}
@end
To call you need only
[[MyCllass sharedInstance] sharedMethod];
When do you use a Singleton class it is created only a one instance the first time it is requested and thereafter ensures that no other instance can be created. And is not possible to you calling copy, release or retain in a instance of singleton class.
I recommend to read a @CocoaSamurai blog post about use of singletons "Singletons: You're doing them wrong"
See ya