Thread safe instantiation of a singleton

前端 未结 5 2111
栀梦
栀梦 2020-12-04 08:28

Which one synchronization method to use to ensure a singleton remains a singleton?

+(Foo*)sharedInstance
{
   @synchronized(self)
   {
      if (nil == _shar         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 08:42

    If anyone cares, here is a Macro for the same thing:

       /*!
        * @function Singleton GCD Macro
        */
        #ifndef SINGLETON_GCD
        #define SINGLETON_GCD(classname)                            \
                                                                    \
        + (classname *)shared##classname {                          \
                                                                    \
            static dispatch_once_t pred;                            \
            static classname * shared##classname = nil;             \
            dispatch_once( &pred, ^{                                \
                shared##classname = [[self alloc] init];            \
            });                                                     \
            return shared##classname;                               \
        }                                                           
        #endif
    

提交回复
热议问题