In short, you can understand @Selector() Is to take the class method number, his behavior can basically be equivalent to the function pointer in C language, but in C language, the function name can be directly assigned to a function pointer, andObjective-CThe class cannot directly apply the function pointer, so only one @SelectorSyntax.
The result is a sel type. Is this type essentially the number (function address) of the class method )? Therefore, we have the followingCode.
1. Obtain the selector value.
C function pointer
- Int add (INT Val)
- {
- Return Val + 1;
- }
-
-
- INT (* c_func) (INT Val); // defines a function pointer variable.
- _ FUNC = add; // assign the ADDR address of the function to c_func.
Objective-C selector,
- @ Interface foo
- -(INT) Add: int val;
- @ End
-
-
- Sel class_func; // defines a class method pointer
- Class_func = @ selector (add: INT );
Note 1. @ selector is the method to find the current class, and [object @ selector (method name: method parameter...)]; is the celebration method of the class corresponding to the object.
NOTE 2: When you look up a class method, in addition to the method name, the method parameters are also one of the query conditions.
Note 3. You can use a string to find the method sel variable name = nsselectorfromstring (the string of the method name );
Note 4. You can use the SEL variable to reverse query the method name string.
- Nsstring * variable name = nsstringfromselector (SEL parameter );
2. Execute the selector value.
After obtaining the matching value, how can we handle the SEL value? This is still the same as the function pointer, that is, executing it.
Function pointer execution (the following are equivalent forms)
- * C_func (10 );
- C_func (10 );
Sel variable execution. Use the performselecor Method for execution.
- [Object: withobject: parameter 1 withobject: parameter 2];
3. Application scenarios of Selector
SelectorEssentially, it is the same as the callback function of C. It is mainly used for loosely coupled communication between two objects. This method is used in many development environments. For example, GTK and Delphi. Basically, the object between the entire cocoa database and communication between controls are built on this basis.