Create singleton using GCD's dispatch_once in Objective-C

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

    To create thread safe singleton you can do like this:

    @interface SomeManager : NSObject
    + (id)sharedManager;
    @end
    
    /* thread safe */
    @implementation SomeManager
    
    static id sharedManager = nil;
    
    + (void)initialize {
        if (self == [SomeManager class]) {
            sharedManager = [[self alloc] init];
        }
    }
    
    + (id)sharedManager {
        return sharedManager;
    }
    @end
    

    and this blog explain singleton very well singletons in objc/cocoa

提交回复
热议问题