단일 예제 MJ

2410 단어
// Singleton.h
//           ,      ARC  ARC  ;     ,           ,         
// alloc       allocWithZone:

// .h     
#define SingletonH(methodName) + (instancetype)share##methodName;

// .m     
#if __has_feature(objc_arc) //  ARC
#define SingletonM (methodName) \
static id _instance = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone { \
if (_instance == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
} \
return _instance; \
} \
 \
- (id)init { \
static dispatch_once_t onceToken; \
dispatch_once( &onceToken, ^{ \
_instance = [super init]; \
}); \
return _instance; \
} \
 \
+ (id)copyWithZone:(struct _NSZone *)zone { \
    return _instance; \
} \
 \
+ (id)mutableCopyWithZone:(struct _NSZone *)zone { \
return _instance; \
} \
 \
+ (instancetype)share##methodName { \
return [[self alloc] init]; \
}
#else //   ARC
#define SingletonM (methodName) \
static id _instance = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone { \
if (_instance == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
} \
return _instance; \
} \
 \
- (id)init { \
static dispatch_once_t onceToken; \
dispatch_once( &onceToken, ^{ \
_instance = [super init]; \
}); \
return _instance; \
} \
 \
+ (id)copyWithZone:(struct _NSZone *)zone { \
    return _instance; \
} \
 \
+ (id)mutableCopyWithZone:(struct _NSZone *)zone { \
return _instance; \
} \
 \
+ (instancetype)share##methodName { \
return [[self alloc] init]; \
} \
 \
- (oneway void)release { \
 \
} \
 \
- (id)retain { \
return self; \
} \
 \
- (NSInteger)retainCount { \
return 1; \
}
//          \, \                 
// LYSoundTool.h
#import 
#import “Singleton.h”
@interface LYSoundTool : NSObject
SingletonH(SoundTool) //  .h      SingletonH   
@end
// LYSoundTool.m
#import “LYSoundTool.h”
@interface LYSoundTool()
@end
@implementation LYSoundTool
SingletonM(SoundTool) //  .m      SingletonM   
@end
// LYHttpTool.h
#import 
#import “Singleton.h”
@interface LYHttpTool : NSObject 
SingletonH(HttpTool)
@end
// LYHttpTool.m
#import “LYHttpTool.h”
@implementation LYHttpTool
SingletonM(HttpTool)
@end

좋은 웹페이지 즐겨찾기