GCD单例:
static ModulesManager * sharedManager = nil;
+ (id)sharedInstance { static dispatch_once_t once; dispatch_once(&once, ^{ sharedManager = [[self alloc] init]; }); return sharedManager; }
为了防止外界通过alloc方法申请到另一块内存,只生成单个实例,需要覆盖父类的allocWithZone方法 需要注意线程安全
+(id)allocWithZone:(struct _NSZone *)zone{ @synchronized(self){ if (sharedManager == nil) { sharedManager = [super allocWithZone:zone]; //所有的初始化操作在这里进行,因为所有的初始化都会走这个接口 } } return sharedManager; } +(id)copyWithZone:(struct _NSZone *)zone{ return sharedManager; }