块内函数的返回值 [英] Return value for function inside a block

查看:128
本文介绍了块内函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AFNetworking从服务器获取数据:

I am using AFNetworking to get data from a server:

-(NSArray)some function {
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            NSArray *jsonArray =[JSON valueForKey:@"posts"];
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {}
}

所以我在这里要做的是将jsonArray返回给函数.显然退货行不通.

So what I am trying to do here is to return the jsonArray to the function. Obviously return is not working.

推荐答案

您不能使用完成功能块为您的方法创建返回值. AFJSONRequestOperation异步执行其工作. someFunction将在操作仍在进行时返回.成功和失败模块是您在需要的地方获得结果值的方法.

You can't use the completion Block to create a return value for your method. The AFJSONRequestOperation does its work asynchronously. someFunction is going to return while the operation is still working. The success and failure Blocks are how you get resulting values where they need to go.

这里的一个选项是将调用者作为参数传递给包装方法,以便完成功能块可以传递数组.

One option here is to pass in the caller as an argument to your wrapper method so that the completion Block can hand the array off.

- (void)goFetch:(id)caller
{
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        [caller takeThisArrayAndShoveIt:[JSON valueForKey:@"posts"]];
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {}
}

您还可以使调用者创建并传递一个成功运行的Block.然后goFetch:不再需要知道调用方上存在哪些属性.

You could also make your caller create and pass a Block to be run on success. Then goFetch: no longer needs to know what properties exist on the caller.

- (void)goFetch:(void(^)(NSArray *))completion
{
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        if( completion ) completion([JSON valueForKey:@"posts"]);
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {}
}

这篇关于块内函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆