How to call performSelectorInBackground with a function having arguments?

Sasha Grievus picture Sasha Grievus · May 14, 2013 · Viewed 16.1k times · Source

Sorry for the newbie question (maybe). I'm developing an app for ios and i'm trying to execute an external xml reading out of the main thread in order not to freeze the ui while the call is doing its magic.

This is the only way i know to made a process not to execute in the main thread in objective c

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

so i did incapsulate my call into a function

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

Now i have to make the string indXML be a parameter of the function in order to call different xml as i need to. Something like

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

In this case, how the call to performSelector change? If i do it in the usual way i get syntax errors:

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

Answer

Mike Pollard picture Mike Pollard · May 14, 2013
[self performSelectorInBackground:@selector(callXml:)
                       withObject:@"test"];

ie: what you pass in as withObject: becomes the parameter to your method.

Just as a point of interest here's how you could do it 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's on the main thread (updating the UI for example)
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateGUI];
    });
});