How to call a performSelectorInBackground function with a function with arguments?

Sorry for the newbie question (maybe). I am developing an application for ios and I am trying to do an external xml reading from the main thread so as not to slow down the ui while the call does its magic.

This is the only way I know so that the process does not execute on the main thread in object c

[self performSelectorInBackground:@selector(callXml) withObject:self]; 

so i included my call in function

  - (void)callXml{ [RXMLElement elementFromURL:[NSURL URLWithString:indXML]]; } 

Now I need the indXML string to be the parameter of the function to call another xml as I need. Something like

  - (void)callXml:(NSString *) name{ [RXMLElement elementFromURL:[NSURL URLWithString:indXML]]; } 

In this case, how will the call to the Selector function change? If I do this in the usual way, I get syntax errors:

 [self performSelectorInBackground:@selector(callXml:@"test") withObject:self]; 
+8
ios objective-c performselector
source share
5 answers
 [self performSelectorInBackground:@selector(callXml:) withObject:@"test"]; 

ie: what you pass as with Object: becomes the parameter of your method.

How interesting how you could do this using GCD:

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self callXml:@"test"]; // If you then need to execute something making sure it on the main thread (updating the UI for example) dispatch_async(dispatch_get_main_queue(), ^{ [self updateGUI]; }); }); 
+15
source share

For this

 - (void)callXml:(NSString *) name{ [RXMLElement elementFromURL:[NSURL URLWithString:indXML]]; } 

You can call it that

  [self performSelectorInBackground:@selector(callXml:) withObject:@"test"]; 

If your method has a parameter, then : used with the method name and pass parameter as an argument withObject

+8
source share

The selector you use must exactly match the name of the method - the name of the method includes a colon (:). Therefore, your selector should be:

 @selector(callXml:) 

If you want to pass a parameter.

If you need to transfer more complex data, you have 3 options:

  • Pass an NSArray or NSDictionary containing the parameters
  • Passing a custom object that contains all the necessary data as attributes
  • Use GCD ( link GCD_libdispatch )
+1
source share

Hi try this

  RXMLElement *rootXML= [self performSelectorInBackground:@selector(callXml:) withObject:@"test"]; - (RXMLElement *)callXml:(NSString *) name{ NSLog(@"%@",name);//Here passed value will be printed ie test return [RXMLElement elementFromURL:[NSURL URLWithString:indXML]]; } 
+1
source share

Since performSelectorInBackground:withObject: takes only one argument of the object. One way around this limitation is to pass a dictionary (or array) of arguments to the wrapper method, which deconstructs the arguments and calls your actual method.

0
source share

All Articles