#import <Foundation/Foundation.h> @interface FuCardSettings : NSObject + (FuCardSettings *)sharedInstance ; @end
#import "FuCardSettings.h"
@implementation FuCardSettings
//================= 单例 ============== start
static FuCardSettings *sharedSettings = nil;
+ (FuCardSettings *)sharedInstance {
if(sharedSettings == nil){
sharedSettings = [[[self alloc] init]autorelease];
}
return sharedSettings;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedSettings == nil) {
sharedSettings = [super allocWithZone:zone];
}
}
return sharedSettings;
}
+ (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMax;
}
- (oneway void)release {
}
- (id)autorelease {
return self;
}
//================= 单例 ============== end
@end
上面是传统的单例:
还有一种用GCD实现的单例:
#import <Foundation/Foundation.h>
@interface Tool1 : NSObject
@property(nonatomic,copy)NSString *test;
+ (instancetype)instance;
@end
@implementation Tool1
+ (instancetype)instance
{
static Tool1* tool;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
tool = [[Tool1 alloc] init];
});
return tool;
}
- (instancetype)init
{
self = [super init];
if (self) {
_test = @"test";
}
return self;
}
@end
该写法具有以下几个特性:
1. 线程安全。
2. 满足静态分析器的要求。
3. 兼容了ARC
原文:http://my.oschina.net/u/936286/blog/407151