6
typedef struct objc_selector  *SEL;

In the code above, SEL type in objective-c is a pointer to struct objc_selector. So, if I make a SEL variable like:

SEL aSel = @selector(instanceMethod) //Like this

What happens? What did @selector do to the instance method, instanceMethod?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
MiguelC
  • 298
  • 1
  • 3
  • 10

2 Answers2

25

Internally, SEL is equivalent to const char[] that simply holds method name. In fact, they are just C strings:

(lldb) p _cmd
(SEL) $0 = "windowDidLoad"
(lldb) p (const char*) _cmd
(const char *) $1 = 0x91ae954e "windowDidLoad"

The important exception is that these pointers are globally unique in the process, even across static modules and dynamic library boundaries, so they are comparable using ==. Unlike C strings which can not be compared by pointer values ("instanceMethod" == @selector(instanceMethod) may and will fail), selectors are comparable by pointer value: no matter how selector was created, two SEL values for the same selector are always equal.

@selector(instanceMethod) syntax creates C string "instanceMethod" then passes to Obj-C runtime function which turns it into unique pointer value corresponding to that string. What it basically does is

SEL sel = @selector(instanceMethod);
SEL sel = sel_registerName("instanceMethod");

P.S. struct objc_selector does not exist, it is to make SEL values incompatible with C strings, and hide selector implementation details from you. For even better understanding, you may read in Obj-C runtime source code for selectors what those sel_getName and sel_registerName actually do.

hamstergene
  • 24,039
  • 5
  • 57
  • 72
  • 3
    To emphasize that last point; **do not treat SEL as compatible with `char*`.**. That is an implementation detail that *might* change in the future (it probably won't for compatibility reasons... but it could). – bbum Oct 11 '13 at 17:51
  • 3
    This is great information, concisely stated, and not covered in the answers to the other question that this question supposedly duplicates. Thanks! – Ian Lovejoy Aug 29 '15 at 00:48
11

The @selector directive simply takes a method name and returns an appropriate identifier for that method. This identifier is used to determine which method to invoke when the selector does eventually get performed:

SEL aSel = @selector(instanceMethod);

// Calls -instanceMethod on someObject
[someObject performSelector:aSel];

You can find details in Apple's documentation.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356