Nomaly我用來建立一個單身以下幾招:在Objective-c中的單例類上設置init可配置變量的好方法是什麼?
+ (MyClass *)sharedInstance
{
static MyClass *_sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[self alloc] init];
// Init variables
});
return _sharedInstance;
}
然後我可以調用方法如下:
[[MyClass sharedInstance] anyInstanceMethod];
但是,發生什麼事時,任何初始化變量是從類的外部配置屬性? 我的方法是創建兩個類方法,用配置屬性變量其中之一:
+ (MyClass *)sharedInstanceWithVariableOne:(NSString*)aParamOne andVariableTwo:(NSString*)aParamTwo
{
static MyClass *_sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[self alloc] init];
// Init configurables variables
_sharedInstance.paramOne = aParamOne;
_sharedInstance.paramTwo = aParamTwo;
});
return _sharedInstance;
}
,第二個作爲代理這最後一個使用默認值:
+ (MyClass *)sharedInstance
{
return [MyClass sharedInstanceWithVariableOne:@"value1" andVariableTwo:@"value2"];
}
所以,如果你想使用帶配置變量的單例類,您應該首先調用sharedInstanceWithVariableOne:andVariableTwo
,然後再調用sharedInstance
。 我認爲這種方法不是最好的,我期待着使用他人。
在此先感謝。
爲什麼你不喜歡嗎? –
我覺得這種模式有點可疑。考慮多次調用'sharedInstanceWithVariableOne:...'會發生什麼。只有第一組參數會產生任何影響,其他參數將獲得相同的共享實例,但不會與預期的參數一起使用。每個配置都應該是一個單獨的對象,或者這些參數應該是共享實例的屬性,只要您需要更改它們就可以設置這些屬性。 – omz
Anoop Vaidya,我認爲這可能會有更好的方法。這可能會讓人感到困惑和不明顯。 – martinezdelariva