Cocoa-cocoa如何实现单态(singleton)类实例?
苹果官方建议使用以下方式来实现单态模式:
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我现在在用的实现:
static Sample* __sharedSampleManager = nil;
@implementation Sample
+(Sample*) sharedSampleManager
{
return __sharedSampleManager;
}
+(void) initialize
{
static BOOL __bInitialize = false;
if(!__bInitialize)
{
__bInitialize = true;
__sharedSampleManager = [[self alloc] init];
}
}
-(void) dealloc
{
[super dealloc];
[__sharedSampleManager release];
__sharedSampleManager = nil;
}
@end
线程安全:
定义宏:
#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block)
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = block();
});
return _sharedObject;
+(id)sharedInstance
{
DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
return [[self alloc] init];
});
}