Objective-C: Checking class type, is it better to use isKindOfClass or is ToSelector responding?

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];
        }
    }
}
+5
source share
4 answers

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] .

+2

!

, , - ?

respondsToSelector: , , , - , - . .

, - , , . , , , , , , , , , isKindOfClass:, .

, , - ; respondsToSelector: , , , , . , , :

- (int)sources;

respondsToSelector:, , .

, ? , , , API ..

+6

C respondsToSelector:. C , . respondsToSelector: , - - .

, , , . . , WidgetWithSources, , sources? , respondsToSelector:. , , isKindOfClass. Readability, , WidgetWithSources sources. respondsToSelector: , , . -.

: @benzado .

+5

@Tim @benzado, , :

  • - -, , , isKindOfClass: , NSData NSColor NSString ; NSColor isKindOfClass: , , .
  • , , respondsToSelector: , , Apple - respondsToSelector: ( ).
  • If you have a link to different classes, and you check to see if they adhere to some unofficial protocol, then:

    • If this is the code you manage, you can go to the formal protocol and then use it conformsToProtocol:as a test. This has the advantage of testing for a type, not just a name; otherwise
    • If this is code that you do not control, use respondsToSelector:, but we know that this is only a check that a method with the same name exists, and not that it takes the same types of arguments.
+3
source

All Articles