注:本文搬移自我自己的博客园http://www.cnblogs.com/NerdFooProgrammer/p/4870260.html
当希望在一个应用程序中某个类的对象只能存在一个的时候就可以考虑用单例模式来实现,单例模式在C++中比较容易实现(只需把构造函数声明为private),而在Objective-C中对象可以通过NSObject的alloc来产生,所以需要编写一些额外的代码来确保对象的唯一性,考虑到现在编写iOS APP代码几乎都是ARC方式,且GCD也已经被用烂了,故本文给出一种利用GCD技术来实现严格单例模式的ARC版本。
源码实现
Singleton.h
@interface Singleton : NSObject
@property(nonatomic,strong) NSString *name;
+(Singleton*)defaultManager;
@end
Singleton.m
@implementation Singleton
//单例类的静态实例对象,因对象需要唯一性,故只能是static类型
static Singleton *defaultManager = nil;
/**单例模式对外的唯一接口,用到的dispatch_once函数在一个应用程序内只会执行一次,且dispatch_once能确保线程安全
*/
+(Singleton*)defaultManager
{
static dispatch_once_t token;
dispatch_once(&token, ^{
if(defaultManager == nil)
{
defaultManager = [[self alloc] init];
}
});
return defaultManager;
}
/**覆盖该方法主要确保当用户通过[[Singleton alloc] init]创建对象时对象的唯一性,alloc方法会调用该方法,只不过zone参数默认为nil,因该类覆盖了allocWithZone方法,所以只能通过其父类分配内存,即[super allocWithZone:zone]
*/
+(id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t token;
dispatch_once(&token, ^{
if(defaultManager == nil)
{
defaultManager = [super allocWithZone:zone];
}
});
return defaultManager;
}
//自定义初始化方法,本例中只有name这一属性
- (instancetype)init
{
self = [super init];
if(self)
{
self.name = @"Singleton";
}
return self;
}
//覆盖该方法主要确保当用户通过copy方法产生对象时对象的唯一性
- (id)copy
{
return self;
}
//覆盖该方法主要确保当用户通过mutableCopy方法产生对象时对象的唯一性
- (id)mutableCopy
{
return self;
}
//自定义描述信息,用于log详细打印
- (NSString *)description
{
return [NSString stringWithFormat:@"memeory address:%p,property name:%@",self,self.name];
}
测试代码
Singleton *defaultManagerSingleton =[Singleton defaultManager];
NSLog(@"defaultManagerSingleton:\n%@",defaultManagerSingleton);
Singleton *allocSingleton = [[Singleton alloc] init];
NSLog(@"allocSingleton:\n%@",allocSingleton);
Singleton *copySingleton = [allocSingleton copy];
NSLog(@"copySingleton:\n%@",copySingleton);
Singleton *mutebleCopySingleton = [allocSingleton mutableCopy];
NSLog(@"mutebleCopySingleton:\n%@",mutebleCopySingleton);
//打印结果
2015-10-11 21:48:34.722 Singleton[1941:214584] defaultManagerSingleton:
memeory address:0x7fa6d1591530,property name:Singleton
2015-10-11 21:48:34.727 Singleton[1941:214584] allocSingleton:
memeory address:0x7fa6d1591530,property name:Singleton
2015-10-11 21:48:34.727 Singleton[1941:214584] copySingleton:
memeory address:0x7fa6d1591530,property name:Singleton
2015-10-11 21:48:34.727 Singleton[1941:214584] mutebleCopySingleton:
memeory address:0x7fa6d1591530,property name:Singleton
从打印结果来看通过 [Singleton defaultManager]、[[Singleton alloc] init]、[allocSingleton copy]、[allocSingleton mutableCopy]这四种方法生成的对象地址都是0x7fa6d1591530,即表明对象是同一个,也就实现了严格单例模式,加上GCD是线程安全的所以在多线程中也能保证对象的唯一性。
另:在学习Objective-C编写单例模式时看到网上好多人都借用苹果官方的实现方式,但我自己始终没搜到官方的实现Sample代码,如果你知道麻烦把网址给我发下,谢谢哈~