Singleton in iOS 5?

前端 未结 3 1877
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 10:17

Hi I had an implementation previous versions of iOS for a singleton as follows:

.h file

@interface CartSingleton : NSObject 
{

}
+(CartSingleton *)          


        
3条回答
  •  借酒劲吻你
    2020-11-30 11:06

    The dispatch_once snippet is functionally identical to other one. You can read about it at http://developer.apple.com/library/mac/#documentation/Darwin/Reference/Manpages/man3/dispatch_once.3.html.

    This is what I use for singletons:

    + (MySingleton*) getOne {
        static MySingleton* _one = nil;
    
        @synchronized( self ) {
            if( _one == nil ) {
                _one = [[ MySingleton alloc ] init ];
            }
        }
    
        return _one;
    }
    

    NOTE: In most cases, you do not even need to use @synchronized (but it is safe this way).

提交回复
热议问题