단일 사례 - 매크로를 통한 단일 사례

1903 단어
를 생성합니다.h 파일, 코드는 다음과 같습니다.
#ifdef __has_feature(objc_arc) // ARC   

//.h  
#define singleton_h(name) +(instancetype)sharad##name;
//.m  
#define singleton_m(name) static id _instanceType = nil;\
+(instancetype)sharad##name\
{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _instanceType = [[self alloc]init];\
    });\
    return _instanceType;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _instanceType = [super allocWithZone:zone];\
    });\
    return _instanceType;\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
    return _instanceType;\
}

#else //MRC   

//.h       ##
#define singleton_h(name) +(instancetype)sharad##name;

//.m      
#define singleton_m(name) static id _instanceType = nil;\
+(instancetype)sharad##name\
{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _instanceType = [[self alloc]init];\
    });\
    return _instanceType;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _instanceType = [super allocWithZone:zone];\
    });\
    return _instanceType;\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
    return _instanceType;\
}\
-(oneway void)release\
{\
\
}\
-(instancetype)retain\
{\
    return _instanceType;\
}\
-(instancetype)autorelease\
{\
    return _instanceType;\
}\
- (NSUInteger)retainCount\
{\
    return 1;\
}

#endif

4
  • 단일 클래스를 만들어야 할 때 1.이 파일 가져오기 2.단례류의.h파일
    #import "singleton.h"
    @interface DBTools : NSObject
    singleton_h(     )
    @end
    

    3. 단례류에서.m 파일 중
    @implementation DBTools
    singleton_m(     )
    @end
    

    이렇게 하면 단일 클래스를 신속하게 실현하고 조건 컴파일을 통해 MRC와 ARC의 판단을 진행하여 서로 다른 메모리 관리 모델에서 상응하는 방법을 실현한다.
  • 좋은 웹페이지 즐겨찾기