iOS从方法返回块值

Dm *_*Kuz 1 block ios objective-c-blocks

如何从方法和输出块中返回变量"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" ????

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 5

根本问题是网络请求是异步运行的(即,在方法返回之后,您想要"返回"的值将无法使用),因此您无法像您所概述的那样使用它.你能做到这一点的唯一方法是使请求同步,这是一个非常糟糕的主意.

相反,您应该接受异步模式.特别是不要尝试使用doubleafter 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
}
Run Code Online (Sandbox Code Playgroud)