您可以通过多种方式创建单例。我想知道这些之间哪个更好。
+(ServerConnection*)shared{
static dispatch_once_t pred=0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
我可以看到这编译得非常快。我认为检查谓词将是另一个函数调用。另一个是:
+(ServerConnection*)shared{
static ServerConnection* connection=nil;
if (connection==nil) {
connection=[[ServerConnection alloc] init];
}
return connection;
}
两者之间有什么重大区别吗?我知道这些可能足够相似,不用担心。但只是想知道。
主要区别在于,第一个使用Grand Central Dispatch来确保创建单例的代码只运行一次。这向您保证它将是一个单例。
GCD 还应用了威胁安全性,因为根据规范,对dispatch_once的每个调用都将同步执行。
我会推荐这个
+ (ConnectionManagerSingleton*)sharedInstance {
static ConnectionManagerSingleton *_sharedInstance;
if(!_sharedInstance) {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[super allocWithZone:nil] init];
});
}
return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
取自这里 http://blog.mugunthkumar.com/coding/objective-c-singleton-template-for-xcode-4/
编辑:
这是您所问的答案http://cocoasamurai.blogspot.jp/2011/04/singletons-your-doing-them-wrong.html
编辑 2:
前面的代码是针对 ARC 的,如果要非 arc 支持添加
#if (!__has_feature(objc_arc))
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release {
//do nothing
}
- (id)autorelease {
return self;
}
#endif
(完全按照第一个链接的说明)
最后对单例有一个很好的解释:
http://csharpindepth.com/Articles/General/Singleton.aspx