When we have a method name and a parameter list and want to dynamically send a message to an object, it can be implemented using a reflection function mechanism, and there are two common practices:
First, Performselector
1 -(ID) performselector: (SEL) aselector; 2 -(ID) Performselector: (SEL) aselector withobject: (ID)object; 3 -(ID) Performselector: (SEL) aselector withobject: (ID) object1 withobject: (ID ) Object2;
There are three commonly used methods, of which aselector can be obtained through the Nsselectorfromstring method
SEL aselector = nsselectorfromstring (selstring);
But the disadvantage of performselector is that it only supports passing two parameters
http://my.oschina.net/ososchina/blog/644117
The method given in this article is two that can support multiple parameters, but I tried the next unsuccessful
Second, nsinvocation
Not much to say, directly on the chestnuts
//Test Reflection function- (void) Printwithstring: (NSString *)stringWithnum: (NSNumber *) number Witharray: (Nsarray *) Array {NSLog (@"%@, %@, %@",string, Number, array[1]);}- (void) Test {nsstring*str =@"ha ha haha"; NSNumber*num = @ -; Nsarray*arr = @[@"ABC",@"DEF"];//[self printwithstring:str withnum:num Witharray:arr];Sel sel = nsselectorfromstring (@"PrintWithString:withNum:withArray:"); Nsarray*OBJS =[Nsarray arraywithobjects:str, num, arr, nil]; [Self Performselector:sel withobjects:objs];}- (ID) Performselector: (SEL) selector withobjects: (Nsarray *) objects{//Method Signature (description of the method)Nsmethodsignature *signature = [selfclass] Instancemethodsignatureforselector:selector]; if(Signature = =Nil) { //you can throw an exception or you can not manipulate it. } //nsinvocation: Wrapping a method call (method caller, method name, method parameter, method return value) with a Nsinvocation objectNsinvocation *invocation =[Nsinvocation invocationwithmethodsignature:signature]; Invocation.target=Self ; Invocation.selector=selector; //Setting ParametersNsinteger Paramscount = signature.numberofarguments-2;//number of arguments except self, _cmdParamscount =MIN (Paramscount, Objects.count); for(Nsinteger i =0; i < Paramscount; i++) { ID Object=Objects[i]; if([ObjectIskindofclass:[nsnullclass]])Continue; [Invocation setargument:&ObjectAtindex:i +2]; } //Calling Methods[invocation invoke]; //Get return value IDReturnValue =Nil; if(signature.methodreturnlength) {//There is a return value type to get the return value[Invocation getreturnvalue:&ReturnValue]; } returnreturnvalue;}
IOS reflex functions: Performselector and Nsinvocation