Note that there are some explanatory texts on larger screens.

plurals
  1. PONSTimer as a timeout mechanism
    text
    copied!<p>I'm pretty sure this is really simple, and I'm just missing something obvious. I have an app that needs to download data from a web service for display in a UITableView, and I want to display a UIAlertView if the operation takes more than X seconds to complete. So this is what I've got (simplified for brevity):</p> <p><strong>MyViewController.h</strong></p> <pre><code>@interface MyViewController : UIViewController &lt;UITableViewDelegate, UITableViewDataSource&gt; { NSTimer *timer; } @property (nonatomic, retain) NSTimer *timer; </code></pre> <p><strong>MyViewController.m</strong></p> <pre><code>@implementation MyViewController @synthesize timer; - (void)viewDidLoad { timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(initializationTimedOut:) userInfo:nil repeats:NO]; [self doSomethingThatTakesALongTime]; [timer invalidate]; } - (void)doSomethingThatTakesALongTime { sleep(30); // for testing only // web service calls etc. go here } - (void)initializationTimedOut:(NSTimer *)theTimer { // show the alert view } </code></pre> <p>My problem is that I'm expecting the <code>[self doSomethingThatTakesALongTime]</code> call to block while the timer keeps counting, and I'm thinking that if it finishes before the timer is done counting down, it will return control of the thread to <code>viewDidLoad</code> where <code>[timer invalidate]</code> will proceed to cancel the timer. Obviously my understanding of how timers/threads work is flawed here because the way the code is written, the timer never goes off. However, if I remove the <code>[timer invalidate]</code>, it does.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload