Bla*_*ckM 13 block objective-c afnetworking
我正在使用AFNetworking从服务器获取数据:
-(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) {}
}
Run Code Online (Sandbox Code Playgroud)
所以我在这里要做的是将jsonArray返回给函数.显然返回不起作用.
Jos*_*ell 19
您无法使用完成块为方法创建返回值.在AFJSONRequestOperation异步执行其工作.someFunction当操作仍然有效时,它将返回.成功和失败块是您如何获得他们需要的结果值.
这里的一个选择是将调用者作为参数传递给包装器方法,以便完成块可以关闭数组.
- (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) {}
}
Run Code Online (Sandbox Code Playgroud)
您还可以让调用者创建并传递一个块以便在成功时运行.然后goFetch:不再需要知道调用者上存在哪些属性.
- (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) {}
}
Run Code Online (Sandbox Code Playgroud)