Create singleton using GCD's dispatch_once in Objective-C

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

    You can avoid that the class be allocated with overwriting the alloc method.

    @implementation MyClass
    
    static BOOL useinside = NO;
    static id _sharedObject = nil;
    
    
    +(id) alloc {
        if (!useinside) {
            @throw [NSException exceptionWithName:@"Singleton Vialotaion" reason:@"You are violating the singleton class usage. Please call +sharedInstance method" userInfo:nil];
        }
        else {
            return [super alloc];
        }
    }
    
    +(id)sharedInstance
    {
        static dispatch_once_t p = 0;
        dispatch_once(&p, ^{
            useinside = YES;
            _sharedObject = [[MyClass alloc] init];
            useinside = NO;
        });   
        // returns the same object each time
        return _sharedObject;
    }
    

提交回复
热议问题