Popcorn
Popcorn

Reputation: 5348

Why does respondsToSelector: exist?

Why do we have to manually check this every time we try to send a message to an object that might not respond to the message/selector? Why can't the language do the check for us every time a message is sent, or every time performSelector: or the variants of this message gets called. This would eliminate all crashes due to sending invalid messages.

Is it too inefficient to do this?

Upvotes: 2

Views: 133

Answers (1)

rmaddy
rmaddy

Reputation: 318894

There are a few good reasons why every method call doesn't have a built-in check. First, it would be pretty inefficient. But more importantly, in most cases you should only be calling known methods so there is no need for a check.

But there are various reasons why we do want to check at runtime. Protocols with optional methods are a prime case. Working with different versions of the API is another common reason. New methods get added or removed over time.

We need to be able to tell the difference between a mistake and knowing that we are calling a method that may or may not exist. When it is a mistake, we want the failure and exception. When a method is optional, we need to do the runtime check so that the call can be skipped if it doesn't exist.

Upvotes: 3

Related Questions