AFNetworking可以同步返回数据(在块内)吗? [英] Can AFNetworking return data synchronously (inside a block)?
问题描述
我有一个使用AFJSONRequestOperation的函数,我希望仅在成功后返回结果。你能指出我正确的方向吗?我仍然对块和AFNetworking特别无能为力。
I have a function using AFJSONRequestOperation, and I wish to return the result only after success. Could you point me in the right direction? I'm still a bit clueless with blocks and AFNetworking specifically.
-(id)someFunction{
__block id data;
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json){
data = json;
return data; // won't work
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation: operation];
return data; // will return nil since the block doesn't "lock" the app.
}
推荐答案
阻止执行主线程直到操作完成,你可以在添加到操作队列后执行 [operation waitUntilFinished]
。在这种情况下,您不需要块中的 return
;设置 __ block
变量就足够了。
To block the execution of the main thread until the operation completes, you could do [operation waitUntilFinished]
after it's added to the operation queue. In this case, you wouldn't need the return
in the block; setting the __block
variable would be enough.
这就是说,我强烈反对强制异步操作同步方法。有时候让你头脑发热是很棘手的,但如果有任何方法你可以将它构造成异步,那几乎肯定是要走的路。
That said, I'd strongly discourage forcing asynchronous operations to synchronous methods. It's tricky to get your head around sometimes, but if there's any way you could structure this to be asynchronous, that would almost certainly be the way to go.
这篇关于AFNetworking可以同步返回数据(在块内)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!