GCD单例:
+ (id)sharedInstance { static ModulesManager * sharedManager = nil; static dispatch_once_t once; dispatch_once(&once, ^{ sharedManager = [[self alloc] init]; }); return sharedManager; }
为了防止外界通过alloc方法申请到另一块内存,只生成单个实例,需要覆盖父类的allocWithZone方法 需要注意线程安全
+(id)allocWithZone:(struct _NSZone *)zone{ @synchronized(self){ if (sharedSingleton == nil) { sharedSingleton = [super allocWithZone:zone]; } } return sharedSingleton; } +(id)copyWithZone:(struct _NSZone *)zone{ return sharedSingleton; }
时间: 2024-09-11 00:35:17