What is @selector?
11 Types of SEL
2 represents the message (method) you want to send, it's a bit like a string, or you can turn it around.: Nsselectorfromstring ()/nsselectorfromstring ()
3 something that can be understood as a function pointer--a thing that allows objective-c to invoke methods dynamically.--is the object-c dynamic post-binding technique a function pointer that can be accessed through a string
4 is actually the message response function---Select a function address for the message response to your action
[Email protected] (function_name) that gets the ID of a function
The OBJC_MSGXXX series functions are global
Performselector is the NSObject member method, the MS effect is almost objective-c dynamic post-bind technology: The function pointer can be accessed through a string typedef obj_handler * SEL; IOS SEL (@selector) Principle and Usage summary (i)
A pointer to the SEL class member method
It can be understood that @selector () is the number of the class method, his behavior is basically equivalent to the C language of the function pointer, except that the C language, can be directly assigned to a function pointer, and the OBJECT-C class cannot directly apply the function pointer, This can only be done with a @selector syntax to fetch.
The result is an SEL type. The type essence is the number of the class method (function Address)
C + + function pointers
int test (int val)
{
return val+1;
}
Int (* c_func) (int val); Define a function pointer variable c_func = add; Assign the function addr address directly 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 a way to find the current class (with subclasses).
Example:
Parent class. h file
[Plain]View Plaincopy
- #import <Foundation/Foundation.h>
- @interface Selectordemo:nsobject
- {
- SEL _methodtest;
- }
- @property (nonatomic,assign) SEL methodtest;//is declared here as an attribute convenient for external incoming.
- -(void) Testparentmethod;
- -(void) Testsubmethod;
- @end
. m file
[Plain]View Plaincopy
- #import "SelectorDemo.h"
- @implementation Selectordemo
- @synthesize methodtest = _methodtest;
- -(void) Parentmethod
- {
- NSLog (@ "Parent method call success!");
- }
- -(void) Testparentmethod
- {
- if (_methodtest)
- {
- [Self performselector:_methodtest withobject:nil];
- }
- }
- -(void) Testsubmethod
- {
- if (_methodtest)
- {
- [Self performselector:_methodtest withobject:nil];
- }
- }
- @end
Sub-class:
. h file
[Plain]View Plaincopy
- #import <Foundation/Foundation.h>
- #import "SelectorDemo.h"
- @interface Selectorsub:selectordemo
- @end
. m file
[Plain]View Plaincopy
- #import "SelectorSub.h"
- @implementation Selectorsub
- -(void) Submethod
- {
- NSLog (@ "Sub method call success!");
- }
- @end
Make a Test call.
[Plain]View Plaincopy
- Selectorsub *SS = [[Selectorsub alloc]init];
- Ss.methodtest = @selector (Parentmethod);
- [SS Testparentmethod];
- Ss.methodtest = @selector (Submethod);
- [SS Testparentmethod];
- [SS release];
Ss.methodtest = @selector (Parentmethod); This sentence, when run, looks for a method in the parent class to call.
Ss.methodtest = @selector (Submethod);//This sentence is at run time, the parent class is searched first, and if the parent class does not, the subclass is sought.
If this is ss.methodtest = @selector (test); Where test is not the SS-parent class, nor the SS itself, nor the SS subclass, which is used at this time
[Self performselector:_methodtest withobject:nil]; There will be an address looking for an error.
[CPP]View Plaincopy
- The following is actually a good explanation of why it must be a class or subclass of itself.
[CPP]View Plaincopy
- [friend Performselector: @selector (gossipabout:) Withobject:aneighbor];
Equivalent to:[CPP]View Plaincopy
- [friend Gossipabout:aneighbor];
[CPP]View Plaincopy
[CPP]View Plaincopy
- With this principle, when the property is set to the SEL type, if the callback mechanism uses a class or subclass that is not a SEL declaration. To implement callbacks for other classes, you must pass in the context handle of the other class.
[CPP]View Plaincopy
- Example:
[CPP]View Plaincopy
- The Selectordemo class above is modified to read:
[Plain]View Plaincopy
- #import <Foundation/Foundation.h>
- @interface Selectordemo:nsobject
- {
- SEL _methodtest;
- ID _handle;
- }
- @property (nonatomic,assign) SEL methodtest;
- @property (nonatomic,retain) ID handle; Add an instance handle property for another class.
- -(void) Testparentmethod;
- -(void) Testsubmethod;
- @end
[Plain]View Plaincopy
- #import "SelectorDemo.h"
- @implementation Selectordemo
- @synthesize methodtest = _methodtest;
- @synthesize handle = _handle;
- -(void) Parentmethod
- {
- NSLog (@ "Parent method call success!");
- }
- -(void) Testparentmethod
- {
- if (_methodtest)
- {
- [_handle performselector:_methodtest withobject:nil];//the original self belongs to the corresponding instance handle
- }
- }
- -(void) Testsubmethod
- {
- if (_methodtest)
- {
- [_handle performselector:_methodtest Withobject:nil];
- }
- }
- @end
Here I want to be familiar with the ios,target-action mode, are clear.
Target-action design mode
In the handling of user-interface controls, AppKit fully leverages the ability to change receivers and messages at run time.
The NSControl object is a graphics device that can be used to send instructions to the application. Most of the control devices in the real world are implemented, such as button, switch, knob, text field, Dial, menu item, etc. In software, these devices are located between the user and the application. They interpret events from hardware devices, such as keyboards and mice, and translate them into application-specific instructions. For example, a button named "Find" will translate the mouse click event into an application instruction to start the search.
AppKit defines a template for creating a control device and defines some of its own off-the-shelf devices. For example, the Nsbuttoncell class defines an object that can be assigned to an Nsmatrix instance and initializes its size, name, picture, font, and keyboard shortcut. When the user taps the button (or uses a keyboard shortcut), the Nsbuttoncell object sends a message indicating that the application is working. To do this, the Nsbuttoncell object not only initializes the image, size, and name, but also determines where and to whom the message is to be sent. Accordingly, the Nsbuttoncell instance can initialize an action message (the object selector that it will use in the message it sends) and a target (the object that receives the message).
[CPP]View Plaincopy
- [Mybuttoncell setaction: @selector (reapthewind:)];
- [Mybuttoncell Settarget:anobject];
When the user clicks on the corresponding button, the button unit will use the NSObject protocol method Performselector:withobject: send the message. All action messages have a single parameter that is the ID of the control device that sent the message.
If Objective-c does not allow the message to be changed, all Nsbuttoncell objects will have to send the same message, and the name of the method will be written dead in the Nsbuttoncell source code. Unlike simple implementations that convert user action to action messages, button cells and other controls have to restrict the content of the message. Restricted messages make it difficult for many objects to respond to more than one button cell. Either the button has a target, or the target object can find the message from the button and handle it accordingly. Each time you re-layout the user interface, you must also implement a method that responds to the action message. The lack of dynamic messaging will cause unnecessary trouble, but objective-c avoids it well.
As you can tell from the previous example, if the SEL is not its own method, it will make a mistake at the time of the call, causing crash and how to avoid the error caused by the message delivery. See the following article:
Avoid message errors
If an object receives a message to execute a method that does not belong to it, it produces an incorrect result. This is the same kind of error as calling a non-existent function. However, because the message occurs at run time, the error occurs only after the program executes.
Handling this error is relatively easy when the message selector is a constant and the Receiving object class is known. When you write a program, you can make sure that the recipient is able to respond. If the receiver is a static type, the compiler will complete the test for you.
However, if the message selector or receiver is changing, then the test can only be performed at run time. The Respondstoselector: Method defined in the NSObject class can test whether a recipient can respond to a message. It takes the method selector as a parameter and returns whether the recipient has accessed a method that matches the selector:
[CPP]View Plaincopy
- if ([AnObject respondstoselector: @selector (setorigin::)])
- [AnObject setorigin:0.0:0.0];
- Else
- fprintf (stderr, "%s can ' t be placed\n",
- [Nsstringfromclass ([AnObject class]) utf8string]);
Respondstoselector: Runtime testing is important when you send a message to an object that you cannot control at compile time. For example, if you write a piece of code to send a message to an object, and this object is a variable that someone else can set a value for, then you need to make sure that the receiver implements the method that should respond to the message.
Note: An object can forward the message to other objects when it receives a message that is not itself responsible for a direct response. In this case, from the caller's point of view, the object processes the message directly, even though the object is handled by forwarding the message to other objects.
Note 2. When looking for a class method, in addition to the method name, the method parameter also queries one of the conditions.
This is primarily a number of parameters to be aware of, such as:
[CPP]View Plaincopy
- SEL Setwidthheight;
- Setwidthheight = @selector (setwidth:height:);
Note 3, you can use the string to find the method SEL variable name = nsselectorfromstring (string of method name);
Note 4, can be run with the SEL variable to detect the method name string, such as: NSString *method = Nsstringfromselector (setwidthheight);
Note 5, the SEL lookup method does not support the class method (that is, static method, in C + + with the static keyword, in the object-c is the method with the + sign, Delphi is the class function).
iOS develops a simple summary of SEL
Sel is a wrapper for the method. Package SEL type data it corresponds to the corresponding method address and can be called by locating the method address. The methods of each class in memory are stored in the class object, each method has a corresponding SEL type of data, according to a SEL data can find the corresponding method address, and then call the method .
- @interface Person:nsobject
- + (void) test1;
- -(void) test2;
- @end
- //According to the person class and method defined in the. h file, this line of code is executed in memory as follows
- Person *person = [[Person alloc] init];
SEL is a wrapper for the method. Package SEL type data it corresponds to the corresponding method address, find the method address to call the method
1. Where to store the method
- The methods of each class in memory are stored in the class object
- Each method has a corresponding SEL type of data
- The corresponding method address can be found based on a SEL data, which in turn calls the method
- Definition of SEL type: typedef struct OBJC_SELECTOR *sel
Creation of 2.SEL objects
- SEL S1 = @selector (test1); //Wrap the Test1 method into a Sel object
- SEL s2 = nsselectorfromstring (@"test1"); //Convert a string method to a Sel object
Other uses of 3.SEL objects
- Convert a Sel object to a NSString object
- NSString *str = Nsstringfromselector (@selector (test));
- Person *p = [person new];
- Call the test method of the 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 (@"non-Parametric object method");
- }
- -(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 invoke a method:
- 1. Calling directly from the method name
- 2. Indirectly through the SEL data to invoke
- */
- int main (int argc, const char * argv[])
- {
- Person *person = [[Person alloc] init];
- //1. When executing this line of code, the Test2 is packaged into SEL type data
- //2. Then find the corresponding method address according to the SEL data (compare consumption performance but the system will have cache)
- //3. Call the corresponding method according to the method address
- [Person test1];
- //The method is packaged directly into the SEL data type to invoke Withobject: Incoming parameters
- [Person Performselector: @selector (test1)];
- [Person Performselector: @selector (test2:) withobject:@"incoming parameters"];
- return 0;
- }
Understanding and application of @selector in iOS development