單例目前一般有兩種寫法,我早期在ios4,5的時候,一般採用如下寫法
方法一:
static XxxManager *shared = nil;
+ (XxxManager *)sharedManager {
if (!shared) {
shared = [[self allocWithZone:NULL] init];
}
return shared;
}
方法二:
+ (XxxManager *)sharedManager
{
static XxxManager *sharedInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
對比這兩種寫法,
第一種比較常規,符合C的習慣,也是曾經蘋果的推薦寫法。
第二種寫法好處是用到了GCD的dispatch_once_t,這東西就是在多線程中用的,所以可以保證線程安全,同時這種方式也能很好的支持了ARC。
不過使用單例的時候需要注意:在單例初始化時,一定不能出現對單例的引用!否者會引起循環調用。
簡單說就是不能在單例類的初始化的方法中,自身或者成員變量又對單例的變量或方法進行調用。
具體參考:http://www.cnblogs.com/sunnyxx/archive/2012/11/09/2762861.html