06. How to Define a singleton?

It will take about 1 minutes to finish reading this article.

We can define a singleton in OC like this:

1
2
3
4
5
6
7
8
+ (instancetype) sharedManager {
static Object *obj = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
obj = [[Object alloc] init];
});
return obj;
}

Use dispatch_once_t in GCD can ensure that the code in it is called only once, so as to ensure the safety of the singleton on the thread. However, since the original Dispatch once method is abandoned in Swift, dispatch_once_t cannot be used to create a singleton. ‘Let’ is a simpler way to ensure thread safety. So the final code is as follows:

Example Code

1
2
3
4
5
6
7
final class SingleOne {
static let shared = SingleOne()
private init() {}

var first: Bool = false
var second: String = ""
}

Reference https://blog.csdn.net/LiqunZhang/article/details/115127156