There are several ways to implement a singleton, such as the following
Class Swiftsingleton { class var Shared:swiftsingleton { if! inner.instance { inner.instance = Swiftsingleton () } return inner.instance! } struct Inner { static var Instance:swiftsingleton? } }
The implementation of this code, the conditional judgment in GKFX, If inner.instance. Generates an instance for NULL, this code is simple to see that when the thread accesses the Swiftsingleton.shared method at the same time, the following problems arise, thread A determines that inner.instance is empty, switches to thread B immediately after entering the IF statement, and thread B Also Because thread a just enters the IF statement, this line of code
Inner.instance = Swiftsingleton ()
Did not execute, at this time inner.instance is still empty, purebred B also made an if statement, in this case will create multiple instances, there is no guarantee that the uniqueness of the instance. 2, using GCD technology to achieve a single case mode
Class Swiftsingleton { class var Shared:swiftsingleton { dispatch_once (&inner.token) { Inner.instance = Swiftsingleton () } return inner.instance! } struct Inner { static var Instance:swiftsingleton? static var token:dispatch_once_t = 0 } }
Swift Single case