Create singleton using GCD's dispatch_once in Objective-C

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

    MySingleton.h

    @interface MySingleton : NSObject
    
    +(instancetype)sharedInstance;
    
    +(instancetype)alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
    -(instancetype)init __attribute__((unavailable("init not available, call sharedInstance instead")));
    +(instancetype)new __attribute__((unavailable("new not available, call sharedInstance instead")));
    -(instancetype)copy __attribute__((unavailable("copy not available, call sharedInstance instead")));
    
    @end
    

    MySingleton.m

    @implementation MySingleton
    
    +(instancetype)sharedInstance {
        static dispatch_once_t pred;
        static id shared = nil;
        dispatch_once(&pred, ^{
            shared = [[super alloc] initUniqueInstance];
        });
        return shared;
    }
    
    -(instancetype)initUniqueInstance {
        return [super init];
    }
    
    @end
    

提交回复
热议问题