通過調用isKindOfClass檢查類的類型是否更合適:或者通過僅檢查它是否支持您通過respondsToSelector查找的方法來執行「duck typing」方法:?Objective-C:檢查類的類型,最好使用isKindOfClass或respondsToSelector?
這裏是我想的,兩種方式編寫代碼:
for (id widget in self.widgets)
{
[self tryToRefresh:widget];
// Does this widget have sources? Refresh them, too.
if ([widget isKindOfClass:[WidgetWithSources class]])
{
for (Source* source in [widget sources])
{
[self tryToRefresh:source];
}
}
}
或者:
for (id widget in self.widgets)
{
[self tryToRefresh:widget];
// Does this widget have sources? Refresh them, too.
if ([widget respondsToSelector:(@selector(sources))])
{
for (Source* source in [widget sources])
{
[self tryToRefresh:source];
}
}
}
檢查這個線程http://stackoverflow.com/questions/4913055/iphone-is-using-iskindofclass-considered-bad-practice-in-any-way – 2012-07-16 18:37:07
需要注意的是,在一般情況下,動態不鼓勵檢查班級的類型。委託模式之外的選擇器響應也一樣。 – bbum 2012-07-16 19:57:47