Objective C - sample Singleton implementation

前端 未结 6 984
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 07:37

*I definitely need a break... cause was simple - array was not allocated... Thanks for help. Because of that embarrassing mistake, I flagged my post in order to delete i

6条回答
  •  误落风尘
    2020-12-20 08:38

    After web reading and personal practicing, my current singleton implementation is:

    @interface MySingleton
    
    @property myProperty;
    +(instancetype) sharedInstance;
    
    @end
    
    
    @implementation MySingleton
    
    + (instancetype) sharedInstance
    {
        static dispatch_once_t pred= 0;
        __strong static MySingleton *singletonObj = nil;
        dispatch_once (&pred, ^{
            singletonObj = [[super allocWithZone:NULL]init];
            singletonObj.myProperty = initialize ;
        });
    
        return singletonObj;
    }
    
    +(id) allocWithZone:(NSZone *)zone
    {
        return [self sharedInstance];
    }
    
    -(id)copyWithZone:(NSZone *)zone
    {
        return self;
    }
    

    this is a thread safe implementation and avoids the risk to create new objects by calling "alloc init" on your class. Attributes initialization has to occur inside the block, not inside "init" override for similar reasons.

提交回复
热议问题