Original address: http://www.cnblogs.com/ygm900/archive/2013/01/16/2862676.html
There are several ways to transfer functions in various languages: a function pointer can be used in C, a function reference in C + +, a functor and a lambda,objective-c, and a selector (selector) and a block.
However, since most of the APIs in the iOS SDK are selector, this article focuses on selector.
Objective-c differs from other object-oriented languages that I have touched, and it emphasizes message passing, not method invocation. So you can pass any message to an object without having to make a statement about how these messages are handled at compile time.
Obviously, since the compile time does not determine the address of the method, then the runtime needs to be self-locating. and Objective-c runtime is through "ID objc_msgsend (ID thereceiver, SEL theselector, ...)" This function to invoke the method. Where Thereceiver is the calling object, Theselector is the message name, and the ellipsis is the indeterminate parameter of the C language.
The message name here is the SEL type, which is defined as struct objc_selector *. However, the documentation does not reveal what Objc_selector is, but provides a @selector instruction to generate:
SEL selector = @selector (message);
The @selector is computed at compile time, so it is not a function call. Further testing shows that it is a C-style string (char*) under Mac OS X 10.6 and iOS:
NSLog (@ "%s", (char *) selector);
You will find that the result is the message name.
Let's write a test class:
@interface Test:nsobject
@end
@implementation Test
-(NSString *) inttostring: (nsinteger) Number {
return [NSString stringwithformat:@ "%d", number];
}
-(NSString *) doubletostring: (double *) Number {
return [NSString stringwithformat:@ "%f", *number];
}
-(NSString *) pointtostring: (cgpoint) Point {
return [NSString stringwithformat:@ "{%f,%f}", Point.x, Point.y];
}
-(NSString *) intstostring: (Nsinteger) Number1 Second: (Nsinteger) number2 Third: (Nsinteger) Number3 {
return [NSString stringwithformat:@ "%d,%d,%d", Number1, Number2, Number3];
}
-(NSString *) doublestostring: (Double) number1 second: (double) number2 third: (double) Number3 {
return [NSString stringwithformat:@ "%f,%f,%f", Number1, Number2, Number3];
}
-(NSString *) combinestring: (NSString *) string1 withsecond:string2 withthird:string3 {
return [NSString stringwithformat:@ "%@,%@,%@", string1, string2, string3];
}
@end
Again to test the objc_msgsend:
#import <objc/message.h>
To use objc_msgsend, you need to introduce this header file.
Test *test = [[Test alloc] init];
Cgpoint point = {123, 456};
NSLog (@ "%@", Objc_msgsend (Test, @selector (pointtostring:), point));
[Test release];
The result is "{123.000000, 456.000000}". And as previously guessed, the following calls are also possible:
NSLog (@ "%@", Objc_msgsend (test, (SEL) "pointtostring:", point));
See here you should find that this implementation can only determine the message name and number of parameters, and the parameter type and return type is erased. So the compiler can only warn you at compile time that the parameter type is not correct, and you cannot prevent you from passing a parameter of the wrong type.
Then look at some of the ways that the NSObject protocol delivers messages:
- -(ID) Performselector: (SEL) Aselector
- -(ID) Performselector: (SEL) Aselector withobject: (ID) anobject
- -(ID) Performselector: (SEL) Aselector withobject: (ID) anobject withobject: (ID) anotherobject
Don't feel very silent? Why must the parameter be an object? Why are only 2 parameters supported?
Fortunately, selector itself does not care about parameter types, so it is OK to pass a thing that is not an object:
NSLog (@ "%@", [Test Performselector: @selector (inttostring:) Withobject: (ID) 123]);
However, double and struct cannot be passed this way because they do not have the same number of bytes as pointers. If you want to use Performselector, you can only modify the parameter type as a pointer:
-(NSString *) doubletostring: (double *) Number {
return [NSString stringwithformat:@ "%f", *number];
}
Double number = 123.456;
NSLog (@ "%@", [Test Performselector: @selector (doubletostring:) Withobject: (ID) (&number)]);
Parameter type is done, but to support a number of parameters, but also to pay the strength. Ideally, we should be able to implement these 2 methods:
@interface NSObject (Extend)
-(ID) Performselector: (SEL) aselector withobjects: (Nsarray *) objects;
-(ID) Performselector: (SEL) aselector withparameters: (void *) Firstparameter, ...;
@end
First look at the former, Nsarray requires that all elements must be objects, and cannot be nil, so the scope of application is still limited. But don't underestimate it, because you will find it impossible to use objc_msgsend, because you can't predict the number of parameters when you write code.
It's time for Nsinvocation to debut:
@implementation NSObject (Extend)
-(ID) Performselector: (SEL) aselector withobjects: (Nsarray *) objects {
Nsmethodsignature *signature = [self methodsignatureforselector:aselector];
Nsinvocation *invocation = [Nsinvocation invocationwithmethodsignature:signature];
[Invocation settarget:self];
[Invocation setselector:aselector];
Nsuinteger i = 1;
For (ID object in objects) {
[Invocation Setargument:&object atindex:++i];
}
[Invocation invoke];
if ([signature methodreturnlength]) {
ID data;
[Invocation getreturnvalue:&data];
return data;
}
return nil;
}
@end
NSLog (@ "%@", [Test Performselector: @selector (combineString:withSecond:withThird:) Withobjects:[nsarray arraywithobjects:@ "1", @ "2", @ "3", Nil]]);
Here are 3 points to note:
- Because method calls have the self (call object) and _cmd (selector) 2 implicit arguments, the index should start at 2 when the parameter is set.
- Because the parameter is an object, you must pass the pointer, that is, &object.
- A methodreturnlength of 0 o'clock indicates that the return type is void and therefore does not need to get the return value. If the return value is an object, we do not need to create buffer. But if it's a C-style string, array, and so on, you need to malloc yourself and free up memory.
Then implement the 2nd method:
-(ID) Performselector: (SEL) aselector withparameters: (void *) Firstparameter, ... {
Nsmethodsignature *signature = [self methodsignatureforselector:aselector];
Nsuinteger length = [Signature numberofarguments];
Nsinvocation *invocation = [Nsinvocation invocationwithmethodsignature:signature];
[Invocation settarget:self];
[Invocation setselector:aselector];
[Invocation Setargument:&firstparameter atindex:2];
Va_list arg_ptr;
Va_start (Arg_ptr, Firstparameter);
for (Nsuinteger i = 3; i < length; ++i) {
void *parameter = Va_arg (arg_ptr, void *);
[Invocation Setargument:¶meter atindex:i];
}
Va_end (ARG_PTR);
[Invocation invoke];
if ([signature methodreturnlength]) {
ID data;
[Invocation getreturnvalue:&data];
return data;
}
return nil;
}
NSLog (@ "%@", [Test Performselector: @selector (combineString:withSecond:withThird:) withparameters:@ "1", @ "2", @ "3"]) ;
Nsinteger number1 = 1, number2 = 2, Number3 = 3;
NSLog (@ "%@", [Test Performselector: @selector (intsToString:second:third:) Withparameters:number1, Number2, Number3]) ;
Similar to the previous implementation, but because the parameter length is unknown, the [signature numberofarguments] is used. Of course, you can also turn the SEL into a string (available Nsstringfromselector ()) and then look for the number of:.
Va_start, Va_arg and va_end are used when dealing with variable parameters, and it is clear that you are familiar with C language.
However, because the type of the parameter is not known, it can only be set to void *. The program also reported a warning that void * is incompatible with the Nsinteger type. And if you change the parameters to double, then the error is directly. Unfortunately, I don't know how to judge whether a void pointer is pointing to a C data type or to a Objective-c object, so it is best to encapsulate it as a Objective-c object. If you only need to be compatible with the C type, you can remove the & of the Setargument parameter, and then pass the pointer directly in:
Nsinteger number1 = 1, number2 = 2, Number3 = 3;
NSLog (@ "%@", [Test Performselector: @selector (intsToString:second:third:) Withparameters:&number1, &number2 , &number3]);
Double Number4 = 1.0, Number5 = 2.0, Number6 = 3.0;
NSLog (@ "%@", [Test Performselector: @selector (doublesToString:second:third:) Withparameters:&number4, & Number5, &number6]);
[Test release];
As for the NSObject class added PerformSelector:withObject:afterDelay: Other methods, you can also support multiple parameters in this way.
Next, say the _cmd that you just skipped, and it can also be used to implement recursive calls. The following is an example of the Fibonacci sequence:
-(Nsinteger) Fibonacci: (Nsinteger) n {
if (n > 2) {
return [Self fibonacci:n-1] + [self fibonacci:n-2];
}
return n > 0? 1:0;
}
The change to the _cmd implementation becomes this:
return (Nsinteger) [Self performselector:_cmd withobject: (ID) (n-1)] + (Nsinteger) [Self performselector:_cmd withobject :(ID) (n-2)];
or directly with Objc_msgsend:
Return (Nsinteger) objc_msgsend (self, _cmd, n-1) + (Nsinteger) objc_msgsend (self, _cmd, n-2);
But every time through the objc_msgsend to call seems very laborious, there is no way to direct the method call it? The answer is yes, and that will require the use of IMP. The IMP is defined as "ID (*IMP) (ID, SEL, ...)", which is a pointer to a function of the method.
NSObject provides the Methodforselector: method to get the imp, so just modify it a little bit:
-(Nsinteger) Fibonacci: (Nsinteger) n {
Static IMP func;
if (!func) {
func = [self methodforselector:_cmd];
}
if (n > 2) {
Return (Nsinteger) func (self, _cmd, n-1) + (Nsinteger) func (self, _cmd, n-2);
}
return n > 0? 1:0;
}
The running time is now 1/4 less than just a few minutes ago.
By the way. Objective-c powerful dynamics, add a Sum:and to the test class:
Nsinteger sum (id self, SEL _cmd, Nsinteger number1, Nsinteger number2) {
return number1 + number2;
}
Class_addmethod ([Test class], @selector (Sum:and:), (IMP) sum, "[email protected]:ii");
NSLog (@ "%d", [Test sum:1 and:2]);
The last parameter of Class_addmethod is the return value and parameter type of the function, and the details can refer to the Type Encodings document.
OC--(SEL)--message passing mechanism in OC--attached: expansion of the Performselector method