使用 Grand Central Dispatch(GCD)
GCD 将保证你的单例只被实例化一次,即使从多个线程调用也是如此。将此插入到名为 shared
的单例实例的任何类中。
+ (instancetype)shared {
// Variable that will point to the singleton instance. The `static`
// modifier makes it behave like a global variable: the value assigned
// to it will "survive" the method call.
static id _shared;
static dispatch_once_t _onceToken;
dispatch_once(&_onceToken, ^{
// This block is only executed once, in a thread-safe way.
// Create the instance and assign it to the static variable.
_shared = [self new];
});
return _shared;
}