Going through Apache Cordova’s source code, I ran into two lines of code that I’m puzzled about:
//[obj performSelector:normalSelector withObject:command];
objc_msgSend(obj,normalSelector,command);
From Apple’s documentation, there doesn’t seem to be a lot of difference between these two methods.
id objc_msgSend(id theReceiver, SEL theSelector, …)
Sends a message with a simple return value to an instance of a class.
– (id)performSelector:(SEL)aSelectorwithObject:(id)anObject
Sends a message to the receiver with an object as the argument. (required)
What exactly is the difference between these two methods? In the case above, both are sending messages with an object as an argument to a receiving object.
You’re asking the difference between two “methods” but only one of them is actually a method. The
objc_msgSendfunction is, well, a function. Not a method.The
objc_msgSendfunction is the function that you actually call when you invoke any method on any object in Objective C. For example, the following two are basically equivalent:The major difference here is that
objc_msgSenddoes not get type checked by the compiler — or at least, its arguments don’t get type checked against the selector’s parameter types. So the following are roughly equivalent:But, that’s a bit of a waste, since all
performSelector:withObject:does is callobjc_msgSend.HOWEVER: You should stay away from
obc_msgSendbecause it is not type-safe, as mentioned above. All the apache devs are doing is removing a single method call, which will only give you very slight performance benefits in most cases.