xcode 在后台执行 Selector 并获取返回字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4890863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:10:31  来源:igfitidea点击:

Perform Selector In Background and get the return string

iphoneobjective-cxcodeios4nsstring

提问by max_

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.

我正在尝试执行一个在后台线程中返回 NSString 的选择器,返回的 NSString 将取决于输入对象专辑链接。

I am performing it in the background, as it takes a while to shorten the URL.

我在后台执行它,因为缩短 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];

回答by Dan Ray

You can write another method in your class (let's call it -handleResponse:(NSString *)response), and then from the backgrounded process you can call:

您可以在您的类中编写另一个方法(让我们称之为-handleResponse:(NSString *)response),然后您可以从后台进程中调用:

[self performSelectorOnMainThread:@selector(handleResponse:) withObject:@"My response string" waitUntilDone:NO];

回答by Chuck

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.

你不能在它运行的线程之外获得一个函数的返回值。在后台线程中做某事的全部意义在于它被从主线程的正常流程中取出,所以它没有地方可以返回.. 最明智的方法是创建一个在后台执行的块(直接通过 NSOperation 或 GCD),它会更新主线程上的值(如果您之后需要存储该值),或者只执行您的任何操作如果它只在一个代码分支中使用,则将使用该值。