块内函数的返回值我正在使用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) {}}所以我在这里想要做的就是将jsonArray返回给函数。显然退货是行不通的。
3 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
您不能使用完成块为您的方法创建返回值。在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) {}}您还可以使调用者创建并传递一个成功运行的阻止程序。然后,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) {}}
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
正如其他人所说,在处理异步调用时您不能这样做。除了返回期望的数组,还可以传递一个完成块作为参数
typedef void (^Completion)(NSArray* array, NSError *error);-(void)someFunctionWithBlock:(Completion)block {
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSArray *jsonArray =[JSON valueForKey:@"posts"];
if (block) block(jsonArray, nil);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
if (block) block(nil, error);
}}然后在其中调用someFunction。此代码还将为您执行正确的错误处理。
[yourClassInstance someFunctionWithBlock:^(NSArray* array, NSError *error) {
if (error) {
NSLog(%@"Oops error: %@",error.localizedDescription);
} else {
//do what you want with the returned array here.
}}];
Qyouu
TA贡献1786条经验 获得超11个赞
我遇到了此类问题,并通过以下方法解决了。我看到了以上使用块的答案。但是此解决方案当时更适合。该方法的逻辑很简单。您需要将对象及其方法作为参数发送,请求完成后将调用该方法。希望能帮助到你。
+(void)request:(NSString *)link parameters:(NSDictionary *)params forInstance:(id)instance returns:(SEL)returnValue{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:link
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
[instance performSelector:returnValue withObject: responseObject];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[instance performSelector:returnValue withObject:nil];
//NSLog(@"Error: %@", error);
}];}- 3 回答
- 0 关注
- 464 浏览
添加回答
举报
0/150
提交
取消
