It is more appropriate to check the type of the class by calling isKindOfClass :, or use the duck print approach by simply checking to see if it supports the method you are looking for through responseSoSelector :?
Here the code I think of is written in two ways:
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]; } } }
As an alternative:
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]; } } }
A check may be a warning that you are about to make a hacker decision. The widget already knows its class and its selectors.
, . [widget tryToRefresh] .
[widget tryToRefresh]
!
, , - ?
respondsToSelector: , , , - , - . .
respondsToSelector:
, - , , . , , , , , , , , , isKindOfClass:, .
isKindOfClass:
, , - ; respondsToSelector: , , , , . , , :
- (int)sources;
respondsToSelector:, , .
, ? , , , API ..
C respondsToSelector:. C , . respondsToSelector: , - - .
, , , . . , WidgetWithSources, , sources? , respondsToSelector:. , , isKindOfClass. Readability, , WidgetWithSources sources. respondsToSelector: , , . -.
WidgetWithSources
sources
isKindOfClass.
: @benzado .
@Tim @benzado, , :
NSData
NSColor
NSString
If you have a link to different classes, and you check to see if they adhere to some unofficial protocol, then:
conformsToProtocol: