Create singleton using GCD's dispatch_once in Objective-C

后端 未结 10 2466
爱一瞬间的悲伤
爱一瞬间的悲伤 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 07:51

    @interface className : NSObject{
    +(className*)SingleTonShare;
    }
    
    @implementation className
    
    +(className*)SingleTonShare{
    
    static className* sharedObj = nil;
    static dispatch_once_t once = 0;
    dispatch_once(&once, ^{
    
    if (sharedObj == nil){
        sharedObj = [[className alloc] init];
    }
      });
         return sharedObj;
    }
    

提交回复
热议问题