我如何从方法和块外返回变量“myDoub(例如= 65)”?
- (double)executeRequestUrlString:(NSString *)urlString withBlock:(double (^)(double myDoub))block {
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if (!error){
//data = 65; for example
block(data);
}
}];
return block(data); // ???????? This NOT work
}
- (void)viewDidLoad
{
[super viewDidLoad];
//
.......
//
double myNewDouble = [self executeRequestUrlString:fullUrlImage withBlock:^double(double myDoub) {
return myDoub;
}];
// how i can get here variable "myDoub=65" ????
}
最佳答案
根本问题是网络请求正在异步运行(即,要“返回”的值直到方法返回后才完全可用),因此您不能像概述那样使用它。您唯一可以做到的是使请求同步,这是一个非常糟糕的主意。
相反,您应该采用异步模式。具体来说,不要尝试在double
方法之后使用executeRequestUrlString
(因为到达该位置时您将不会检索到该值),而应仅在withBlock
块的上下文中使用它。因此,将所有取决于该double
的代码放入块内:
- (void)executeRequestUrlString:(NSString *)urlString withBlock:(void (^)(double myDoub))block
{
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if (!error){
double val = ... // extract the double from the `data`, presumably
block(val);
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//
.......
//
[self executeRequestUrlString:fullUrlImage withBlock:^(double myDoub) {
// put all of your code that requires `myDoub` in here
}];
// but because the above is running asynchronously, do not try to use `myDoub` here
}
关于ios - iOS从方法返回 block 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25032753/