非ARC項目中,單獨文件修改成ARC:設計模式
項目-Build Phases - Compile Sources - 找到要修改的文件名稱,雙擊,- 寫入"-fobjc-arc"。ui
MRC
spa
#import "Sound.h".net
@implementation Sound設計
static Sound *_soundTool = nil;3d
+ (instancetype)allocWithZone:(struct _NSZone *)zone {orm
if (_soundTool == nil) {get
static dispatch_once_t onceToken;it
dispatch_once(&onceToken, ^{io
_soundTool = [super allocWithZone:zone];
});
}
return _soundTool;
}
- (instancetype)init {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_soundTool = [super init];
});
return _soundTool;
}
- (oneway void)release {
}
- (instancetype)retain {
return self;
}
- (NSUInteger)retainCount {
return 1;
}
+(instancetype)shared {
return [[self alloc]init];
}
ARC
+(instancetype)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
}
return _instance;
}
- (instancetype)init {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super init];
});
return _instance;
}
+ (instancetype)sharedSoundTool {
return [[self alloc] init];
}
Singleton.h 文件,能夠直接使用。適用於MRC和ARC
// 幫助實現單例設計模式
// .h文件的實現
#define SingletonH(methodName) + (instancetype)shared##methodName;
// .m文件的實現
#if __has_feature(objc_arc) // 是ARC
#define SingletonM(methodName) \
static id _instace = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
} \
return _instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super init]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
}
#else // 不是ARC
#define SingletonM(methodName) \
static id _instace = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
} \
return _instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super init]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
\
- (oneway void)release \
{ \
\
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return 1; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
}
#endif