cocoa实现单态(singleton)类实例?

Thinking80s
  • 301
    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;
    }
回复
阅读 4k
1 个回答

apple文档的单例实现方式其实不是很好,没有考虑多线程下的各种情况。
目前比较好的实现方式应该是使用GDC来实现:

+ (MySharedObject *)sharedObject
{
    static MySharedObject *sharedObject_ = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedObject_ = [[MySharedObject alloc] init];
        [sharedObject_ setup];
    });
    
    return sharedObject_;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏