3
votes

I have NSOperationQueue that runs on another thread than the whole application. I'm adding NSOperation to the queue that in main has

-(void)main{
     [self updatePallets];
     NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target:self selector: @selector(updatePallets) userInfo: nil repeats: Yes];
     NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
     [runLoop addTimer:timer forMode: NSRunLoopCommonModes];
     [runLoop run];
}

And it works fine as I wanted. But how to cancel this type of operation. On My main thread I want to for example do something like this:

[queue cancelAllOperations];
[queue waitUntilAllOperationsAreFinished];

And I want to hang main thread and wait until it is finished. And then perform some actions. But It does not cancel any operation (there'is only one with the timer) what I should do? I tried also to add new operation to the queue after dispatcher pop time, but still can't stop it.

1
Did you invalidate timer? [timer invalidate]tuledev
No I just tried to cancel the operation. So I need to have the reference to the timer... Is It possible to cancelAllOperations and then it stop all the operations? Can I add some conditions to runLoop?Patryk Imosa
I am not sure about cancelAllOperations. But with NSTimer, I am using [timer invalidate]tuledev
I created @property (strong, atomic) NSTimer * timer and method -(void)stopOperation{[self.timer invalidate]} after that I get all operations from queue and setting them stopOperation then I put there cancelAllOperations, and then once again get all the operations from queue and they have timer = nil so it should be stopped and removed from queue ?Patryk Imosa
Humh, I will upvote this question for others bro can notice.tuledev

1 Answers

1
votes

I found something like:

Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. OS X can install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.

If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop.

So I added while loop. But I don't know if it is efficient...

while(self.timer.valid && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]);