我有一個控制器註冊爲一個觀察員的很多屬性的意見。這是我們的-observeValueForKeyPath::::
方法:我如何優化這個巨大的if/else如果塊內observeValueForKey
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void*)context
{
if(context == kStrokeColorWellChangedContext)
{
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:kStrokeColorProperty];
}
else if(context == kFillColorWellChangedContext)
{
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:kFillColorProperty];
}
else if(context == kBodyStyleNumChangedContext)
{
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:kBodyStyleNumProperty];
}
else if(context == kStyleChangedContext)
{
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:kStyleProperty];
}
else if(context == kStepStyleChangedContext)
{
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:kStepStyleProperty];
}
else if(context == kFirstHeadStyleChangedContext)
{
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:kFirstHeadStyleProperty];
}
else if(context == kSecondHeadStyleChangedContext)
{
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:kSecondHeadStyleProperty];
}
而實際上還有約3倍以上的這些else if
語句。
你可以看到的一件事是,每個塊都有相同的代碼,這使我認爲可以優化它。
我的最初的想法是爲具有NSDictionary
稱爲keyPathForContextDictionary
,其中鍵是與(的void*
型)Context
後綴的常數,和的值是適當的字符串常量,由Property
後綴表示
然後這個方法只需要一行:
[self setValue:[change objectForKey:NSKeyValueChangeNewKey] forKey:keyPathForContextDictionary[context]];
請注意,我需要使用某種形式的數據結構,以確定使用哪個的keyPath,我不能簡單地用keyPath
參數傳遞到方法。這是因爲有多個視圖具有我正在觀察的相同屬性(例如,顏色井具有color
屬性)。因此,每個視圖都需要確定一個唯一的鍵路徑,該路徑目前是根據上下文確定的
問題在於,您不能使用void*
作爲NSDictionary
中的鍵。那麼......有沒有人對我在這裏可以做的事情有任何建議?
編輯: 這裏的常量是如何定義的一個例子:
void * const kStrokeColorWellChangedContext = (void*)&kStrokeColorWellChangedContext;
void * const kFillColorWellChangedContext = (void*)&kFillColorWellChangedContext;
void * const kBodyStyleNumChangedContext = (void*)&kBodyStyleNumChangedContext;
void * const kStyleChangedContext = (void*)&kStyleChangedContext;
NSString *const kStrokeColorProperty = @"strokeColor";
NSString *const kFillColorProperty = @"fillColor";
NSString *const kShadowProperty = @"shadow";
NSString *const kBodyStyleNumProperty = @"bodyStyleNum";
NSString *const kStyleProperty = @"style";
類型參數的'context'是'無效*'這樣你就可以使用任何你想要的類型。你可以將它改爲一個對象 - 你只需要施放它。所有'k $ THINGYColorWellChangedContext'常量的類型是什麼? –
哦對不起,讓我編輯帖子。但'context'後綴表示'void *','property'後綴表示'NSString *' –
請顯示其中一個常量的聲明。 –