TheEye's answer is totally incorrect and I think it is important for those new to Objective-C to understand how it actually works.
There are no methods in Objective-C. You send messages to objects. That is not just a minor syntax difference, it's a fundamentally different philosophy.
What actually happens when you send the removeAllObjects
message to an object (regardless of whether it is declared as id or NSString*), the runtime looks at the object's isa (is-a) pointer at runtime, which points to that object's definition.
Each object definition has a list of message selectors the object implements. For runtime performance, the system caches the selectors. So it will check to see if the cache already contains that selector. If it does, the runtime jumps to that location and begins executing the code found there. It will also check up the chain of inherited classes to see if any of them implement the message.
If it can't find the message, it will then send the selector to forwardInvocation:
. That happens for all unknown messages. It just so happens that NSObject's default implementation of forwardInvocation:
invokes doesNotRecognizeSelector:
which will crash.
You can test this yourself by implementing forwardInvocation:
on your own class and doing nothing. Then try sending random selectors to an instance of your class. You will see that no errors are raised. This allows you to create proxy objects that inspect, filter, or modify messages destined for another object. You can also impersonate a different class entirely.
The type of a variable declared in the code is only a hint so the compiler can help you catch errors at compile time. At runtime, it doesn't really matter. Objective-C only looks at the isa pointer to determine an object's class and thus what message selectors it supports.
That's also why you can override a class at runtime, add new methods to a class, etc. You can even change an object's type at runtime by changing the isa pointer, which will cause the bytes of that object to be re-interpreted as the new type (Warning: this is advanced stuff so please be careful!)