マクロ定義を使用した単一インスタンスの作成

2037 ワード

//  

#ifndef KCSingleton_h
#define KCSingleton_h

#pragma mark   .h    
//                      className
//##    、     
#define singleton_interface(className) +(className *)shared##className;

#pragma mark   .m
//\           ,       
#define singleton_implementation(className) \
static className *_instance;\
+(id)shared##className{\
    if(!_instance){\
        _instance=[[self alloc]init];\
    }\
    return _instance;\
}\
+(id)allocWithZone:(struct _NSZone *)zone{\
    static dispatch_once_t dispatchOnce;\
    dispatch_once(&dispatchOnce, ^{\
        _instance=[super allocWithZone:zone];\
    });\
    return _instance;\
}

#endif