Create singleton using GCD's dispatch_once in Objective-C

后端 未结 10 2491
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 07:26

If you can target iOS 4.0 or above

Using GCD, is it the best way to create singleton in Objective-C (thread safe)?

+ (instancetype)sharedInstance
{
          


        
10条回答
  •  死守一世寂寞
    2020-11-22 08:11

    //Create Singleton  
      +( instancetype )defaultDBManager
        {
    
            static dispatch_once_t onceToken = 0;
            __strong static id _sharedObject = nil;
    
            dispatch_once(&onceToken, ^{
                _sharedObject = [[self alloc] init];
            });
    
            return _sharedObject;
        }
    
    
    //In it method
    -(instancetype)init
    {
        self = [super init];
      if(self)
         {
       //Do your custom initialization
         }
         return self;
    }
    

提交回复
热议问题