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.

Comments

Popular posts from this blog

LVM: How to remove a volume using pvremove

Using Oracle 11g thru VirtualBox appliance in Mac OS X Lion

Use Shell Editor for Eclipse for editing bash, ksh, csh in Unix/Linux system