我正在使用 AFNetworking 客户端对象,它对 XML 文档发出异步请求并对其进行解析。
还使用 NSNotificationCenter 在文档解析完成时发布通知。
有没有办法在不阻塞主线程的情况下等待通知的发布?
例如代码:
-(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.");
}
基本上我想知道在上述指定区域中需要什么样的代码来确保函数等待直到获取完成?
现在,在获取完成之前,我会在调试控制台中看到“获取完成。”。
我尝试向 TLHTTPClient 类添加 BOOL 标志:
BOOL fetchingFlag;
然后尝试:
while([RESTClient fetchingFlag]) { NSLog(@"fetching...); }
当此类收到通知时,它设置 RESTClient.fetchingFlag = FALSE;从技术上讲,哪个应该杀死 while 循环,对吧?除了我的 while 循环无限运行?!
最佳答案
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 ?
您不需要代码。开始获取后,不要在方法中放入任何内容,否则什么也不会发生。您的程序将“等待”(它实际上正在处理其他输入),直到收到通知。
在通知处理程序方法中,放入获取完成后需要执行的所有操作。这是通知和其他回调方案的要点之一——您的对象在收到采取行动的通知之前不会执行任何进一步的操作。
Is there a way to wait for a notification to be posted without blocking the main thread?
这正是它的工作原理。
关于objective-c - NSNotificationCenter - 等待通知发布而不阻塞主线程的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10231157/