如何等待线程块完成 [英] How to wait for threading blocks to finish

查看:75
本文介绍了如何等待线程块完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中存在线程问题.这是我第一次同时使用AFNetworking和Parse.问题是我要同时调用这两个功能,并且都必须先完成这两个功能,然后才能进行下一个测试.

I am having issues with threading in my app. This is the first time I have used both AFNetworking and Parse. The problem is that I am calling both features and they both are required to finish before moving onto the next segue.

这是我的代码.第一个块用于使用AFHTTP的网络请求,第二个块是解析请求.

Here is my code. The first block is for the network request using AFHTTP and the second is the parse request.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];



PFQuery *query = [PFQuery queryWithClassName:@"dependant"];
[query whereKey:@"parentID" equalTo:[masterAccount getObjectID]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

for (PFObject *dependant in objects) {
   //do some stuff with parse object here           
    }
     [self performSegueWithIdentifier: @"MySegue" sender: self];
     }];

据我所知,这两个都在各自的线程中创建和运行,以便不阻塞gui,这是正确的吗?我应该将segue调用移到哪里(当前在Parse块的末尾),以便在这些请求的 都完全完成之前不会调用它?

To my knowledge, both of these create and run off in their own threads so as to not block the gui, is this correct? Where would I move the segue call (currently at the end of the Parse block) so that it would not be called until both of these requests have fully completed?

推荐答案

一个简单的方法是拥有一个单独的对象,例如ResourceState.给它两个属性,一个属性给gotJsonData,一个属性给gotParseData.在完成处理程序中,只需在ResourceState中调用一个方法即可更新适当的属性(json或parse),如果两个属性均都设置为成功,则会触发segue.我不会尝试采用块内块的方法-它的代码较少,但会使代码难以维护.

A simple way to do this is to have a separate object, say ResourceState. Give it two properties, one for gotJsonData, one for gotParseData. In the completion handlers just call a method in ResourceState which updates the appropriate property (json or parse) and if both properties are set to success, triggers the segue. I would not try to do a block-inside-a-block approach -- it's less code but can make the code hard to maintain.

这里存在的基本问题是,您需要在模型"和视图控制器"之间进行清晰的分隔.我通常的工作方式是让模型完成所有工作,包括网络请求,并且当它知道需要UI端更新时,它会发送NSNotification,主线程上的UI会侦听该NSNotification,然后更新该UI.

The underlying problem you have here is that you need a clean separation between 'model' and 'view controller'. The way I normally work is to have the model do all the work, including network requests, and when it knows a UI-side update is needed, it sends a NSNotification which the UI on the main thread listens to and then updates the UI.

这篇关于如何等待线程块完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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