Wednesday, April 27, 2011

Singleton implementation in iOS on Objective-C

Just read this very helpful article on implementing a singleton in iOS. Below is a simple snippet that is thread safe, and is indeed, faster than @synchorize when is executed.

+(MyClass *)singleton {
 static dispatch_once_t pred;
 static MyClass *shared = nil;
 dispatch_once(&pred, ^{
  shared = [[MyClass alloc] init];
 return shared;

dispatch_once() function is indeed mentioned in Mac Developer Library that is useful in implementing singletons or global data.

Hope you found this helpful.