Perform Selector In Background and get the return string
Solution 1
You can't get a function's return value outside of the thread it runs in. The whole point of doing something in a background thread is that it's taken out of the normal flow for the main thread, so there's no place for it to return to.. The most sensible approach is to create a block that's performed in the background (either through NSOperation or GCD directly) which updates either updates the value on the main thread — if you need to store the value afterward — or which just does whatever you were going to do with the value if it was only going to be used in one branch of code.
Solution 2
You can write another method in your class (let's call it -handleResponse:(NSString *)response
), and then from the backgrounded process you can call:
[self performSelectorOnMainThread:@selector(handleResponse:) withObject:@"My response string" waitUntilDone:NO];
Comments
-
max_ almost 2 years
I am trying to perform a selector which returns an NSString in the background thread, and the NSString returned will depend on the input object albumlink.
I am performing it in the background, as it takes a while to shorten the URL.
I would really appreciate if you could tell me how I could get the return string.
My code to perform that selector is:
[self performSelectorInBackground:@selector(shortenURL:) withObject:albumlink];
-
Richard about 13 yearsYou can -- have the background thread perform a selector on the main thread with the string as the argument.
-
Chuck about 13 years@Richard: Did you read my answer past "You can't"? That's basically what I said to do. What I said you can't do is have a method execute on a different thread but still return a value normally.