ARC Lazy mode
#import"Singleton.h"@implementationSingletonStaticID _instance;This method is called internally by the/** * Alloc method */+ (Instancetype) Allocwithzone: (struct _nszone *) zone{if (_instance = =Nil) {Prevent frequent lock-up@synchronized (self) {if (_instance = nil) {//Prevent creation of multiple _ instance = [super Allocwithzone:zone];}} } return _instance;} + (instancetype) sharedsingleton{if (_instance = nil) {//prevent frequent lock @synchronized (self) {if (_instance = = nil) {//Prevent creation of multiple _ instance = [[self alloc] init];}} } return _instance;} -(id) Copywithzone: (Nszone *) zone{return _instance;} @end
A Hungry man mode (not used)
#import"HMSingleton.h" @implementation singletonstatic id _instance; /** * When a class is loaded into the OC Runtime Environment (memory), it is called once (a class will only load 1 times) */+ (void) load{_instance = [[self alloc] init];} + (Instancetype) Allocwithzone: (struct _nszone *) zone{if (_ Instance = = nil) {//Prevent creation of multiple _instance = [super Allocwithzone:zone]; } return _instance;} + (instancetype) sharedsingleton{return _instance;} -(id) Copywithzone: (Nszone *) zone{return _instance;} @end
GCD Implementing a singleton pattern
@implementationSingletonstatic ID _instance;+ (instancetype) Allocwithzone: (struct _nszone *) zone{ static dispatch_once_t Oncetoken; dispatch_once (&oncetoken, ^{_instance = [super Allocwithzone:zone];}); return _instance;} + (instancetype) sharedsingleton{ static dispatch_once_t Oncetoken; dispatch_once (&oncetoken, ^{_instance = [[Selfalloc] init];}); return _instance;} -(ID) Copywithzone: (Nszone *) zone{ return _instance;} @end
Singleton mode in iOS