我知道2種方法。什麼是更好的?還有什麼比兩種方式更好?共享類實例(創建和共享單例)的最佳方式是什麼?
+ (MyClass *)shared {
/*
static MyClass *sharedInstance = nil;
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
}
return sharedInstance;
*/
/*
static dispatch_once_t pred;
static MyClass *sharedInstance = nil;
dispatch_once(&pred, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
*/
}
這使得它無法配置類實例被創建方法之前。 「dispatch_once」方法是普遍接受的方法;有各種不同的方式來實現相同的事情實際上並沒有幫助。 – gnasher729
我不明白你爲什麼不能配置這個類。你可以在+ load,+ initialize(在創建sharedInstance之前)配置它。在適當的時候,您甚至可以稍後在應用生命週期中更改一些sharedInstance屬性。也許我只是不明白你的意思,當然dispatch_once方法也能工作。 – aLevelOfIndirection