Create singleton using GCD's dispatch_once in Objective-C

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

    instancetype

    instancetype is just one of the many language extensions to Objective-C, with more being added with each new release.

    Know it, love it.

    And take it as an example of how paying attention to the low-level details can give you insights into powerful new ways to transform Objective-C.

    Refer here: instancetype


    + (instancetype)sharedInstance
    {
        static dispatch_once_t once;
        static id sharedInstance;
    
        dispatch_once(&once, ^
        {
            sharedInstance = [self new];
        });    
        return sharedInstance;
    }
    

    + (Class*)sharedInstance
    {
        static dispatch_once_t once;
        static Class *sharedInstance;
    
        dispatch_once(&once, ^
        {
            sharedInstance = [self new];
        });    
        return sharedInstance;
    }
    

提交回复
热议问题