Singelton made simple
In my quest to adopt the new ARC technique introduced with Xcode 4.2 I needed to find a good way to implement the Singelton pattern. The way I did it previously involved overriding methods like retain and release, something that is strongly discouraged in ARC.
The solution I settled with was an extremely simple but effective one and needed only a single method (found on the internet).
- (id)sharedInstance
{
static dispatch_once_t _predicate = 0;
static id _sharedInstance = nil;
dispatch_once(&_predicate, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
That’s all that is needed. But even if it’s very neat it’s not fool proof and it’s still possible to create new instances of the object. But for my needs this is the perfect solution.
Comment this note:
No messages yet.