For the more curious: how selectors work

You learned in Chapter 20 that when you send a message to an object, the object’s class is asked if it has a method with that name. The search goes up the inheritance hierarchy until a class responds with Yeah, I have a method with that name.

Figure 27.4  The search for a method with the right name

The search for a method with the right name

As you can imagine, this search needs to happen very, very quickly. If the compiler used the actual name of the method (which could be very long), method lookup would be really slow. To speed things up, the compiler assigns a unique number to each method name it encounters. At runtime, it uses that number instead of the method name.

Figure 27.5  How it really works

How it really works

Thus, a selector is the unique number that represents a particular method name. When a method expects a selector as an argument (like scheduledTimerWithTimeInterval:​target:​selector:​userInfo:​repeats: does), it is expecting this number. You use the @selector compiler directive to tell the compiler to look up the selector for the given method name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset