I’ve read many articles to understand why it’s necessary to use @selector() to refer to a method, but I don’t think that I’m satisfied. When we specify an action for a button, for example, we have to write:
[btn addTarget:self action:@selector(myMethod)];
Why not simply:
[btn addTarget:self action:myMethod];
Please explain the need and reason, and what happens without it.
It all has to do with parsing the C language.
On its own, in an expression like
[obj performSelector:someRandomSelector]'the compiler treatssomeRandomSelectorbit as “expand whateversomeRandomSelectoris — evaluating expressions, dealing with #defines, laying down a symbol for later linking, etc… — and whatever that expansion yields better be a SEL.Thus, if you were to write
[obj performSelector:action]'the compiler would have no way to know the difference betweenactionas a variable containing a potentially volatile selector andactionbeing the actual name of a method onobj.@selector()solves this by creating a syntactic addition to the language that always evaluates to a constant SEL result.Historically, Objective-C was originally implemented as a straight up extension to the C preprocessor. All the various
@...prefixed additions made that implementation much easier in that basically anything prefixed by an@was an Objective-Cism.