Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when there is no matching method for an Objective-C message?

Tags:

objective-c

I'm a bit puzzled:

  • From Cocoa Programming For Mac OS X (page 63, 3rd edition, Aaron Hillegass): "If it reaches the top of the [inheritance] tree without finding a method, the function throws an exception".

  • From the Wikipedia article on Objective-C: "the object to which the message is directed (referred to as the receiver) is not inherently guaranteed to respond to a message, and if it doesn't it simply ignores it and returns a null pointer."

Which one is it?

like image 451
Arne Evertsson Avatar asked Dec 09 '22 20:12

Arne Evertsson


2 Answers

When a selector is not found, it will go to -[NSObject doesNotRecognizeSelector:]. The default implementation fires off an exception.

like image 133
Tom Dalling Avatar answered May 13 '23 16:05

Tom Dalling


They're both more or less correct. The difference is that the Cocoa framework defines root objects (e.g., NSObject) from which the other classes in the framework inherit; if an object doesn't respond to a message, by default it gets passed up the tree until it reaches a root object, which then throws an exception in Cocoa.

This behavior can be overridden to allow objects to do other things with messages they don't understand.

Other Objective-C frameworks can choose to deal with unrecognized messages in a different way (e.g., by returning a null pointer).

like image 28
mipadi Avatar answered May 13 '23 15:05

mipadi