NSNotificationCenter-在不阻塞主线程的情况下等待通知发布的方式? [英] NSNotificationCenter - Way to wait for a notification to be posted without blocking main thread?

查看:195
本文介绍了NSNotificationCenter-在不阻塞主线程的情况下等待通知发布的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个AFNetworking客户端对象,该对象向XML文档发出异步请求并进行解析.

I'm using an AFNetworking client object which makes an asynchronous request for an XML document and parses it.

还可以使用 NSNotificationCenter 在文档解析完成后发布通知.

Also using NSNotificationCenter to post a notification when the document has finished parsing.

是否有一种方法可以等待在不阻塞主线程的情况下发布通知?

Is there a way to wait for a notification to be posted without blocking the main thread?

例如代码:

-(void)saveConfiguration:(id)sender {

    TLHTTPClient *RESTClient = [TLHTTPClient sharedClient];

    // Performs the asynchronous fetching....this works. 
    [RESTClient fetchActiveUser:[usernameTextField stringValue] withPassword:[passwordTextField stringValue]];

    /*
     * What do I need here ? while (xxx) ?
     */

    NSLog(@"Fetch Complete.");

}

基本上我想知道在上述指定区域中需要什么样的代码才能确保功能等待直到提取完成?

Basically I'm wondering what sort of code I need in the above specified area to ensure that the function waits until the fetch has been completed ?

现在,在提取完成之前,我将在调试控制台中看到提取完成." .

As it is right now I'll see "Fetch Complete." in the debug console before the fetch has been completed.

我尝试将BOOL标志添加到TLHTTPClient类:

I tried adding a BOOL flag to the TLHTTPClient class:

BOOL fetchingFlag;

然后尝试:

while([RESTClient fetchingFlag]) { NSLog(@"fetching...); } 

当此类收到通知时,它将设置RESTClient.fetchingFlag = FALSE;从技术上讲哪个应该杀死while循环正确?除了我的while循环无限运行吗?!

When this class receives the notification it sets RESTClient.fetchingFlag = FALSE; which should technically kill the while loop right? Except my while loop runs infinitely ?!

推荐答案

基本上我想知道在上面指定的区域中需要什么样的代码,以确保该函数一直等到提取完成?

Basically I'm wondering what sort of code I need in the above specified area to ensure that the function waits until the fetch has been completed ?

您不需要没有代码.开始提取后,请勿在方法中放入任何内容,否则将不会发生任何事情.您的程序将等待"(实际上将在处理其他输入),直到收到通知为止.

You need no code. Don't put anything in the method after you start the fetch, and nothing will happen. Your program will "wait" (it will actually be processing other input) until the notification is recieved.

在通知处理程序方法中,放入提取完成后所需执行的所有操作.这是通知和其他回调方案的要点之一-您的对象在收到需要采取行动的通知之前不会做任何进一步的事情.

In the notification handler method, put all the stuff that you need to do when the fetch is completed. This is (one of) the point(s) of notifications and other callback schemes -- your object won't do anything further until it gets the notification that it's time to act.

有没有办法在不阻塞主线程的情况下等待通知的发布?

Is there a way to wait for a notification to be posted without blocking the main thread?

这就是它的工作原理.

这篇关于NSNotificationCenter-在不阻塞主线程的情况下等待通知发布的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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