如何在一段时间后触发委托方法?

发布于 2024-10-07 22:39:58 字数 489 浏览 0 评论 0原文

我正在使用一个异步下载文件的类..工作方式有点像这样

// in AViewController.m
DataGetter *blueFile = [[DataGetter alloc] init];
blueFile.delegate = self;
[blueFile getData:@"http://example.com/blue-file"];

它有一个委托方法,可以在下载后对文件执行操作

- (void) dataGetterFinished:(DataGetter *)dataGetter
{
// code
}

这在理想条件下工作正常,但是当我们处理移动设备时,连接并不总是可靠的。连接可能会中途中断,或者速度可能慢得无法使用。

所以我想知道如何设置一个委托方法,该方法在 10 秒后触发,然后显示错误并停止操作。我必须使用 NSTimer 或 NSNotification 或某种组合吗?

I'm using a class which downloads a file asynchronously .. works a bit like this

// in AViewController.m
DataGetter *blueFile = [[DataGetter alloc] init];
blueFile.delegate = self;
[blueFile getData:@"http://example.com/blue-file"];

It has a delegate method which does stuff to the file once downloaded

- (void) dataGetterFinished:(DataGetter *)dataGetter
{
// code
}

This works OK in ideal conditions, but as we're dealing with a mobile device, connections are not always reliable. The connection might break off half way thru, or it might be unusably slow.

So I'm wondering how I would set up a delegate method which triggers after, say, 10 seconds, which then displays an error and stops the operation. Would I have to use NSTimer, or NSNotification , or some combination?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半岛未凉 2024-10-14 22:39:58

奎因《爱斯基摩人!》来自 Apple 的在 WWDC 2010 上做了两场关于 iPhone 网络编程的演讲。第 207 场和第 208 场,您可以在这里下载:http://developer.apple.com/videos/wwdc/2010/

网络成功的简单接收方法是:

  1. 异步使用 NSURLConnection
  2. 不要不要使用计时器或任何其他方式设置手动超时,默认值是合理的。
  3. 相反,请准备好处理 connection:didFailWithError:,该连接将因超时而发送。
  4. 如果需要,您可以使用 -[NSURLConnection cancel] 手动取消连接,例如响应用户操作。

Quinn "The Eskimo!" from Apple did a two talks on network programming for iPhone at WWDC 2010. It's session 207 and 208, you can download them here: http://developer.apple.com/videos/wwdc/2010/

The simple recepie for network success is:

  1. Use NSURLConnection asynchronously.
  2. Do not set a manual time-out using timers or any other means, the defaults are sane.
  3. Instead be prepared to handle for a connection:didFailWithError:, that will be sent for time-outs.
  4. If needed you can manually cancel a connection using -[NSURLConnection cancel], in response to user action for example.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文