Jac*_*cko 6 iphone singleton objective-c atexit
这是我在研究单身人士文献后所编造的内容.我忘了什么吗?
@implementation MySingleton
static MySingleton *mySharedInstance = nil;
//called by atexit on exit, to ensure all resources are freed properly (not just memory)
static void singleton_remover()
{
//free resources here
}
+ (MySingleton*) sharedInstance{
return mySharedInstance;
}
+ (void)initialize {
if (self == [MySingleton class]) {
mySharedInstance = [[super allocWithZone:NULL] init];
atexit( singleton_remover );
}
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
Run Code Online (Sandbox Code Playgroud)
这在大多数情况下避免了同步锁
如果您希望您的软件可靠,请避免使用“大多数时间”都有效的结构
表 4.1。双重检查锁
双重检查锁是一种尝试,通过在获取锁之前测试锁定标准来减少获取锁的开销。由于双重检查锁可能不安全,因此系统不为它们提供显式支持,并且不鼓励使用它们。