iOS中单例的通用写法(在ARC, MRC下可用), 增加了单线程访问限制.
single.h
#import <Foundation/Foundation.h>
@interface ToolsMRC : NSObject <NSCopying>
+ (instancetype)shareToolsMRC;
@end
single.m
// 考虑MRC优化问题, 防止傻× release单例对象
#import "ToolsMRC.h"
@implementation ToolsMRC
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) {
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
+ (instancetype)shareToolsMRC {
if (_instance == nil) {
@synchronized(self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
}
return _instance;
}
#pragma mark - 重写MRC相关方法
- (oneway void)release {
}
- (instancetype)retain {
return _instance;
}
- (NSUInteger)retainCount {
return 1;
}
- (instancetype)autorelease {
return _instance;
}
- (id)copyWithZone:(NSZone *)zone {
return _instance;
}
@end