使用 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;
}