通过调用 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];
}
}
}