NSOperation with NSTimer循环如何停止它

NSOperation with NSTimer loop how to stop it

我的 NSOperationQueue 在另一个线程上运行,而不是在整个应用程序上运行。我正在将 NSOperation 添加到 main

中的队列中
-(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];
}

而且效果如我所愿。但是如何取消这种操作。例如,在我的主线程上,我想做这样的事情:

[queue cancelAllOperations];
[queue waitUntilAllOperationsAreFinished];

而且我想挂起主线程并等待它完成。然后执行一些操作。但它不会取消任何操作(只有一个带有计时器)我应该怎么做?我也尝试在调度程序弹出时间后向队列添加新操作,但仍然无法停止。

我发现了类似的东西:

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.

所以我添加了 while 循环。但是不知道有没有效率...

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