Question

I am trying to timeout my NSOperation with a NSTimer but my timer is not getting fired. Please see below the code I have written inside my class which is sub classing NSOperation.

- (void)start {
    // Start the timer for Time out before the ping activity starts
    self.timeOutTriggerTimmer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(cancelTheOperation) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:self.timeOutTriggerTimmer forMode:NSDefaultRunLoopMode];

    // Check for cancellation
    if ([self isCancelled]) {
        [self completeOperation];
        return;
    }

    // Executing
    [self willChangeValueForKey:@"isExecuting"];
    executing = YES;
    [self didChangeValueForKey:@"isExecuting"];

    // Begin
    [self beginOperation];
}
Était-ce utile?

La solution

It's easiest to just add the timer to the main run loop, not the current run loop:

[[NSRunLoop mainRunLoop] addTimer:self.timeOutTriggerTimmer forMode:NSDefaultRunLoopMode];

Alternatively, you can keep your timer as it is (scheduled on the current run loop), but then you have to keep the runloop alive, perhaps adding something like the following to the end of the start method (note, Apple recommends this rather than the run method):

while ([self isExecuting] && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

But this (like the run method you contemplated) effectively keep the start method running until execution is done (making what appears to be a concurrent operation to behave more like a non-concurrent operation).

I suspect you're doing this already, but just in case, make sure to invalidate your timer when you complete your operation, or else the timer will retain the operation until the timer fires, unnecessarily delaying the freeing of the operation's resources (and calling the cancelTheOperation even though the operation may well already be done).

Autres conseils

I found the issue. I need to put the below statement to have it executed.

[[NSRunLoop currentRunLoop] run];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top