在objective-c中要实现一个单例类,至少需要做以下四个步骤:
1、为单例对象实现一个静态实例,并初始化,然后设置成nil,
2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,
3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例,
4、适当实现allocWitheZone,copyWithZone,release和autorelease。
下面是一个简单的例子:
static XYLocationManager *sharedInstance = nil;
+ (XYLocationManager *)sharedInstance{
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
});
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
}
return sharedInstance;
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)init {
@synchronized(self) {
self = [super init];
return self;
}
}
原文:http://my.oschina.net/u/1473377/blog/340091