In the iPhone program, a lot of usage such as @ selector will be seen. <IPhone development basics> it took a lot of space to parse this syntax, but I don't know whether it is a translation problem or a poor explanation. until the program uses this syntax and carefully reads some parsing articles. To understand this syntax.
In short, you can understand that @ selector () is the number of the class method. Its 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, while the class of Object-C cannot directly apply the function pointer. In this way, only one @ selector syntax can be used to obtain the function.
The result is a sel type. Is this type essentially the number (function address) of the class method )? Therefore, we have the following code.
1. Obtain the selector value.
C function pointer
int add(int val) { return val+1; }
INT (* c_func) (INT Val ); // Define a function pointer variable
C_func = add; // Assign the ADDR address of the function to c_func.
|
Object-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 for searching 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 parameter is also one of the query conditions. note 3. you can use a string to find a method.
Sel variable name = nsselectorfromstring (method name string );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 SelectorSelector is essentially the same as C's callback function. 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.
From: http://blog.chinaunix.net/uid-9935135-id-181872.html