iOS單例模式的寫法
1倦微、第一種
static AccountManager *DefaultManager = nil;
+ (AccountManager *)sharedManager {
if (!DefaultManager) {
DefaultManager = [[self allocWithZone:NULL] init];
return DefaultManager;
}
}
這種寫法很普通妻味,就是設(shè)置一個(gè)對象類型的靜態(tài)變量,判斷這個(gè)變量是否為nil欣福,來創(chuàng)建相應(yīng)的對象
2.第二種
iOS4.0之后,官方推薦了另一種寫法:
+(AccountManager *)sharedManager{
static AccountManager *defaultManager = nil;
disptch_once_t once;
disptch_once(&once,^{
defaultManager = [[self alloc] init];
}
)
return defaultManager;
}
第二種寫法有幾點(diǎn)好處:
1.線程安全
2.滿足靜態(tài)分析器的要求
3.兼容了ARC
根據(jù)蘋果文檔的介紹
dispatch_once
Executes a block object once and only once for the lifetime of an application.
void dispatch_once(
dispatch_once_t *predicate,
dispatch_block_t block);
Parameters
predicate
A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.
block
The block object to execute once.
Discussion
This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.
If called simultaneously from multiple threads, this function waits synchronously until the block has completed.
The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.
Availability
Available in iOS 4.0 and later.
Declared In
dispatch/once.h
#######從文檔中我們可以看到责球,該方法的主要作用就是在程序運(yùn)行期間,僅執(zhí)行一次block對象拓劝。所以說很適合用來生成單例對象雏逾,其實(shí)任何只需要執(zhí)行一次的代碼我們都可以使用這個(gè)函數(shù)。