正在调用 - [NSRunLoop runUntilDate:]一个好主意? [英] Is calling -[NSRunLoop runUntilDate:] a good idea?

查看:827
本文介绍了正在调用 - [NSRunLoop runUntilDate:]一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常最好拨打 - [NSRunLoop runUntilDate:] ?它似乎没有任何问题,但它让我很紧张,告诉运行循环在运行循环内运行。

Is it generally a good idea to call -[NSRunLoop runUntilDate:]? It seems to work without any issues, but it makes me nervous to tell the run loop to run from within the run loop.

更多信息:

我现在有一个从REST服务获取数据的项目。需要获得的一个关键信息是具有有效数据的日期范围。这只是一小部分数据,只需要获取一次,所以我决定处理它的最佳方法是让属性下载数据,如果局部变量是 nil 。我正在使用 ASIHTTPRequest ASINetworkQueue ,因此默认情况下一切都是异步的,为了使其正常工作,在下载和处理数据之前,此属性无法返回。这是我的代码的大纲,变量的名称已被更改以保护无辜:

I have a project right now that is fetching data from a REST service. One critical piece of information that needs to be obtained is the range of dates with valid data. It's a very small bit of data that only needs to be gotten once, so I decided that the best way to handle it is to have the property download the data if the local variable is nil. I'm using ASIHTTPRequest and an ASINetworkQueue, so everything is asynchronous by default, and in order for this to work, this property can't return until the data has been downloaded and processed. Here's an outline of my code, the names of variables have been changed to protect the innocent:

__block BOOL isWorking = YES;
__block ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:/*actual URL*/] autorelease];
[request setCompletionBlock:^{
    // set local variable
    isWorking = NO;
}];
[request setFailedBlock:^{
    // show alert to user
    isWorking = NO;
}];
[queue addOperation:request];

while (isWorking) {
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}

同样,这似乎工作正常。使用这种方法有任何潜在的问题吗?

Again, this seems to be working fine. Are there any potential issues with using this approach?

推荐答案

你必须确保不要从任何可能的方法中做到这一点由您正在调用的运行循环调用,除非重叠的调用树完全可重入。

You have to make sure not to do this from any method that could be called by the run loop you are invoking, unless the overlapping call tree is completely re-entrant.

Cocoa Touch UI代码没有记录为可重入(事实上,Apple DTS有警告/提示它不是),所以如果你的获取数据处理程序可以通过UI方法(或可以在UI运行循环中调用的其他非重入代码)以任何方式调用,不建议从内部调用UI运行循环。

The Cocoa Touch UI code is not documented as re-entrant (in fact, there are warnings/hints from Apple DTS that it is not), so if your fetch data handler can in any way be called by a UI method (or other non-reentrant code that could be called in the UI run loop), calling the UI run loop from inside it is not recommended.

这篇关于正在调用 - [NSRunLoop runUntilDate:]一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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