ios - iOS从方法返回 block 值

标签 ios block 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" ????

}

最佳答案

根本问题是网络请求正在异步运行(即,要“返回”的值直到方法返回后才完全可用),因此您不能像概述那样使用它。您唯一可以做到的是使请求同步,这是一个非常糟糕的主意。

相反,您应该采用异步模式。具体来说,不要尝试在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/

相关文章:

objective-c - 子类可以在继承方法的参数中的 block 中添加参数吗?

ios - 信号量不等待 ALAssetsLibrary writeImageToSavedPhotosAlbum 方法完成

ios - NSTextStorage 的备用后备存储

ios 关闭一个 Controller 并呈现一个带有动画的 Controller

ios - 当我点击 ios 中的 View 时如何关闭 tableviewcell 中的操作表

html - 如何阻止元素包裹在文本内容上?

css - HTML CSS : How to copy and paste div block elements into Notepad while retaining the white space?

objective-c - 提高代码执行速度

ios - 如何获得 UIImage 的配色方案?

iOS 阻止自省(introspection)