Online already has the method, I here is to copy the next, the original link
http://bj007.blog.51cto.com/1701577/649413
Http://blog.csdn.net/u010124617/article/details/28856711?utm_source=tuicool
The dispatch_once_t here is an integral type for marking, nothing special.
The biggest benefit of using dispatch_once to achieve a single case is thread safety!! This is often asked by the interview that there is a thread-safety problem when creating a single case of database and network operations.
First look at OC.
+ (Accountmanager *) sharedmanager { static accountmanager *sharedaccountmanagerinstance = Nil; static dispatch_once_t predicate; Dispatch_once (&predicate, ^{ = [[Self alloc] init]; }); return sharedaccountmanagerinstance;}
Looking at Swfit, the internal struct is used because the static definition class attribute is not supported in Swift's class at this time.
class swiftsingleton{ class func shareinstance (),swiftsingleton{ struct yrsingleton{ static0 static var Instance:swiftsingleton? = Nil } Dispatch_once (&yrsingleton.predicate,{ yrsingleton.instance=Swiftsingleton () } ) return yrsingleton.instance! }}
iOS oc and Swfit create a singleton with Dispatch_once