- @ Interface Person: NSObject
-
- + (Void) test1;
- -(Void) test2;
- @ End
-
- // Execute this line of code based on the Person class and method defined in the. h file as follows in the memory
- Person * person = [[Person alloc] init];
SEL is a method packaging. The encapsulated SEL data corresponds to the corresponding method address. You can call the method by finding the method address.
1. storage location of the Method
- In memory, methods of each class are stored in class objects.
- Each method has a SEL-type data corresponding to it.
- You can find the corresponding method address based on a SEL data and call the method.
- SEL Type Definition: typedef struct objc_selector * SEL
2. Create a SEL object
- SEL s1 = @ selector (test1); // wrap the test1 method into a SEL object
- SEL s2 = NSSelectorFromString (@ "test1"); // convert a string method to a SEL object
3. Other SEL object usage
- // Convert SEL object to NSString object
- NSString * str = NSStringFromSelector (@ selector (test ));
-
- Person * p = [Person new];
-
- // Call the test method of object p
- [P performSelector: @ selector (test)];
- /******************************* Person. h file **********************************/
-
- # Import <Foundation/Foundation. h>
-
- @ Interface Person: NSObject
-
- -(Void) test1;
-
- -(Void) test2 :( NSString *) str;
-
- @ End
-
- /******************************* Person. m file **********************************/
-
- # Import "Person. h"
-
- @ Implementation Person
-
- -(Void) test1
- {
- NSLog (@ "Object method without Parameters ");
- }
-
- -(Void) test2 :( NSString *) str
- {
- NSLog (@ "method with parameters % @", str );
- }
- @ End
-
- /******************************* Main. m file **********************************/
-
- # Import "Person. h"
- # Import <Foundation/Foundation. h>
-
- /*
- There are two ways to call a method:
- 1. Call the method name directly.
- 2. Indirectly calling through SEL data
- */
-
- Int main (int argc, const char * argv [])
- {
- Person * person = [[Person alloc] init];
- // 1. When this line of code is executed, test2 will be packaged into SEL-type data
- // 2. Find the corresponding method address based on the SEL data (performance consumption is compared, but the system will cache)
- // 3. Call the corresponding method based on the method address
- [Person test1];
- // Wrap the method directly into the SEL data type to call withObject: input parameter
- [Person primary mselector: @ selector (test1)];
- [Person required mselector: @ selector (test2 :) withObject: @ "Incoming parameter"];
- Return 0;
- }